
Problem
Solution
Submissions
Stack using Arrays
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to implement a stack data structure using an array. A stack is a linear data structure that follows the Last In First Out (LIFO) principle. The program should implement the following operations:
- push(x): Add element x to the top of the stack
- pop(): Remove and return the top element from the stack
- top(): Return the top element without removing it
- isEmpty(): Return true if stack is empty, false otherwise
- isFull(): Return true if stack is full, false otherwise
Example 1
- Input:
- push(5)
- push(10)
- top()
- pop()
- isEmpty()
- Output:
- Stack pushed: 5
- Stack pushed: 10
- Stack top: 10
- Stack popped: 10
- Stack empty: 0 (false)
- Explanation:
- Step 1: Push 5 to the empty stack. Stack becomes [5].
- Step 2: Push 10 to the stack. Stack becomes [5, 10].
- Step 3: top() returns 10, which is the top element.
- Step 4: pop() removes and returns 10. Stack becomes [5].
- Step 5: isEmpty() returns false (0) because the stack still contains one element.
Example 2
- Input:
- push(7)
- push(12)
- push(23)
- pop()
- pop()
- pop()
- isEmpty()
- Output:
- Stack pushed: 7
- Stack pushed: 12
- Stack pushed: 23
- Stack popped: 23
- Stack popped: 12
- Stack popped: 7
- Stack empty: 1 (true)
- Explanation:
- Step 1: Push 7 to the empty stack. Stack becomes [7].
- Step 2: Push 12 to the stack. Stack becomes [7, 12].
- Step 3: Push 23 to the stack. Stack becomes [7, 12, 23].
- Step 4: pop() removes and returns 23. Stack becomes [7, 12].
- Step 5: pop() removes and returns 12. Stack becomes [7].
- Step 6: pop() removes and returns 7. Stack becomes [].
- Step 7: isEmpty() returns true (1) because the stack is now empty.
Constraints
- The stack should have a maximum capacity defined at initialization
- Stack overflow should be handled when push() is called on a full stack
- Stack underflow should be handled when pop() or top() is called on an empty stack
- All operations should have O(1) time complexity
- Space Complexity: O(n) where n is the maximum capacity of the stack
Editorial
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. |
Solution Hints
- Use a fixed-size array to store the stack elements
- Use a variable to keep track of the top element's index
- Initialize the top index to -1 to represent an empty stack
- For push() operation, increment the top index and then add the element
- For pop() operation, return the element at the top index and then decrement the top index
- For top() operation, simply return the element at the top index without modifying the index
- For isEmpty(), check if the top index is -1
- For isFull(), check if the top index is equal to the maximum capacity minus 1