Array Implementation of Stack
Array Implementation of Stack
STACK
A better implementation of Stack is usually using linked list unless you are sure of
the number of elements in array. But if you are just starting with data structures
and are not familiar with linked list, you can try implementing stack in an array.
While using array to implement stack is easy, it has limitation that the stack cannot
Operations
There can be many operations on stack like this post, but we will discuss only three
Code
For simplicity reason lets assume the array (which hold stack) to be global and
3
4 // Array to hold the stack
5 int s[MAX];
10
13 */
15 {
16 if (top == MAX-1)
17 {
19 return;
20 }
21 s[++top] = value;
22 }
23
24 /** Pop the top element from stack and returns it. If stack is empty return -1.
25 */
26 int pop()
27 {
28 if (top == -1)
29 {
31 return -1;
32 }
33 return s[top--];
34 }
36 */
37 bool isEmpty()
38 {
40 }
Above code is in way a good code. There are lot of problems, to start with pop
returns -1 when stack is empty which means that -1 cannot be a valid member of
the stack.
Push function should ideally return something to tell its calling function whether or
not it was able to insert element in the stack. printf is not a good way in production
memory will be wasted. In other case, if we want a stack with 500 element, we will
have to change MAX value, which means program need to be compiled again. The
solution to this can be to get the size of stack from the calling function and allocate
memory using malloc (or new in C++). But then we should be cautious about
Time Complexity
All the above operations are constant time operations and takes O(1) time. In fact,
almost all the operations of Stack and Queue are constant time operations, except
Source: http://www.ritambhara.in/array-implementation-of-stack/