Whats in this post?
- Output (not available)
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Background and Explanation of the code
Here we assume in current article, that stack‘s capacity is limited to a certain value and overfilling the stack will cause an error. Though, using the ideas from dynamic arrays implementation, this limitation can be easily avoided.
In spite of capacity limitation, array-based implementation is widely applied in practice. In a number of cases, required stack capacity is known in advance and allocated space exactly satisfies the requirements of a particular task. In other cases, stack’s capacity is just intended to be “big enough”. Its capacity is quite large, but too deep recursion still may result in stack overflow.
Implementation of array-based stack is very simple. It uses top variable to point to the topmost stack’s element in the array.
- Initialy top = -1;
- push operation increases top by one and writes pushed element to storage[top];
- pop operation checks that top is not equal to -1 and decreases top variable by 1;
- peek operation checks that top is not equal to -1 and returns storage[top];
- isEmpty returns boolean (top == -1)