A stack is a linear data structure that serves as a collection of elements, with three main operations: push, pop, and peek. We have discussed these operations in the previous post and covered an array implementation of the stack data structure. In this post, a linked list implementation of the stack is discussed.

Practice this problem

We can easily implement a stack through a linked list. In linked list implementation, a stack is a pointer to the “head” of the list where pushing and popping items happens, with perhaps a counter to keep track of the list’s size.

The advantage of using a linked list over arrays is that it is possible to implement a stack that can grow or shrink as much as needed. Using an array will restrict the maximum capacity of the array, which can lead to stack overflow. Here each new node will be dynamically allocated, so overflow is not possible unless memory is exhausted.

 
The implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Inserting 1
Inserting 2
Inserting 3
The top element is 3
Removing 3
Removing 2
Removing 1
The stack is empty

The time complexity of push and pop operations is O(1).

 
References: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)