Tutorialspoint
Problem
Solution
Submissions

Stack using Array

Certification: Basic Level Accuracy: 62.5% Submissions: 8 Points: 8

Write a Java program to implement a stack using an array. The stack should support the following operations: push, pop, peek, isEmpty, and isFull.

Example 1
  • Input:
    push(10)
    push(20)
    push(30)
    pop()
    peek()
  • Output:
    30 popped from stack
    Top element is: 20
  • Explanation:
    • 30 is removed from top
    • 20 becomes new top
Example 2
  • Input:
    push(10)
    isEmpty()
    push(20)
    push(30)
    isFull()
    pop()
    pop()
    pop()
    isEmpty()
  • Output:
    Stack is not empty
    Stack is not full
    30 popped from stack
    20 popped from stack
    10 popped from stack
    Stack is empty
  • Explanation:
    • Stack behaves correctly under various operations
Constraints
  • Fixed capacity set at initialization
  • Time Complexity: O(1) for all operations
  • Space Complexity: O(n) where n is capacity
  • Must handle overflow and underflow properly
ArraysEYAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use an array to store elements.
  • Keep track of the top element's index.
  • Implement boundary checks for push and pop operations.
  • For push, increment top and then add the element.
  • For pop, return the element and then decrement top.

Steps to solve by this approach:

 Step 1: Create a class with an array, a variable to track the top element, and the maximum capacity.
 Step 2: Initialize the top index to -1 in the constructor (indicating an empty stack).
 Step 3: Implement the push method by incrementing top and then adding the element to that position.
 Step 4: Implement the pop method by returning the element at top and then decrementing top.
 Step 5: Implement the peek method to return the element at top without modifying top.
 Step 6: Implement isEmpty method to check if top is -1.
 Step 7: Implement isFull method to check if top equals maxSize-1.

Submitted Code :