A stack is a linear data structure that follows the LIFO (Last–In, First–Out) order, i.e., items can be inserted or removed only at one end of it.

The stack supports the following standard operations:

  • push: Pushes an item at the top of the stack.
  • pop: Remove and return the item from the top of the stack.
  • peek: Returns the item at the top of the stack without removing it.
  • size: Returns the total number of items in the stack.
  • isEmpty: Checks whether the stack is empty.
  • isFull: Checks whether the stack is full.

 
Here’s a visual demonstration of push and pop operations at the top of the stack.


Data stack

The time complexity of all the above operations is constant.

Practice this problem

Stack Implementation using a List

The stack can easily be implemented as a list. Following is the custom stack implementation in Python, which uses a list:

Download  Run Code


Output:
 
Inserting 1 into the stack…
Inserting 2 into the stack…
Removing 2 from the stack
Removing 1 from the stack
Inserting 3 into the stack…
The top element is 3
The stack size is 1
Removing 3 from the stack
The stack is empty

Using deque()

Python’s library offers a deque object, which stands for the double-ended queue. A deque is a generalization of stacks and queues which support constant-time additions and deletions from either side of the deque in either direction.

Following is a simple example demonstrating the usage of deque to implement stack data structure in Python:

Download  Run Code


Output:
 
Inserting A into the stack…
Inserting B into the stack…
Inserting C into the stack…
Inserting D into the stack…
The top element is D
Removing D from the stack
Removing C from the stack
The stack size is 2
Removing B from the stack
Removing A from the stack
The stack is empty

 
Also See:

Stack Implementation in C

Stack Implementation in C++

Stack Implementation in Java

Stack Implementation using a Linked List – C, Java, and Python