Compare Array Based Vs Linked List Stack Implementations
Compare Array Based Vs Linked List Stack Implementations
Compare Array Based Vs Linked List Stack Implementations
A stack can be easily implemented using the linked list. In stack Implementation, a stack contains a top pointer. which is “head” of the stack where pushing
and popping items happens at the head of the list. First node have null in link field and second node link have first node address in link field and so on and
last node address in “top” pointer.
The main advantage of using linked list over an arrays is that it is possible to implement a stack that can shrink or grow as much as needed. In using array
will put a restriction to the maximum capacity of the array which can lead to stack overflow. Here each new node will be dynamically allocate. so overflow is
not possible.
Stack Operations:
push() : Insert a new element into stack i.e just inserting a new element at the beginning of the linked list.
pop() : Return top element of the Stack i.e simply deleting the first element from the linked list.
peek(): Return the top element.
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".
Striking example of the last concept is an application stack. It's capacity is quite large, but too deep recursion still may result in stack overflow.
Implementation
Implementation of array-based stack is very simple. It uses top variable to point to the topmost stack's element in the array.
1. Initially top = -1;
2. push operation increases top by one and writes pushed element to storage[top];
3. pop operation checks that top is not equal to -1 and decreases top variable by 1;
4. peek operation checks that top is not equal to -1 and returns storage[top];
5. is Empty returns Boolean (top == -1).