Python Program to Implement Stack Using Linked List
Last Updated :
08 Apr, 2024
In Python, creating a stack using a linked list involves implementing a data structure where elements are added and removed in a last-in-first-out (LIFO) manner. This approach uses the concept of nodes interconnected by pointers, allowing efficient insertion and deletion operations. We are given a Linked list and our task is to create a stack using a linked list in Python.
For detailed information, refer to :- Implement a Stack Using Singly Linked List
Implement Stack Using Linked List in Python
Below, is the implementation of Stack using Linked List in Python:
Step 1: Define the Node Class for the Linked List
In the below code, we first define the Node class, which represents individual nodes in the linked list, containing data and a reference to the next node. This step sets up the fundamental structure for our linked list implementation within the stack.
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
Step 2: Define the Stack Class and its Methods
In the below code, we define the Stack class with methods such as is_empty, push, pop, peek, and display to perform stack operations like checking if the stack is empty, adding elements, removing elements, accessing the top element, and displaying the stack contents. This step encapsulates the stack functionality using a linked list.
Python3
class Stack:
def __init__(self):
self.head = None
def isempty(self):
if self.head == None:
return True
else:
return False
def push(self, data):
if self.head == None:
self.head = Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
# Remove element that is the current head (start of the stack)
def pop(self):
if self.isempty():
return None
else:
poppednode = self.head
self.head = self.head.next
poppednode.next = None
return poppednode.data
# Returns the head node data
def peek(self):
if self.isempty():
return None
else:
return self.head.data
# Prints out the stack
def display(self):
iternode = self.head
if self.isempty():
print("Stack Underflow")
else:
while(iternode != None):
print(iternode.data, end="")
iternode = iternode.next
if(iternode != None):
print(" -> ", end="")
return
Step 3: Create an Instance of the Stack Class and Test the Stack Operations
In the below code, we create an instance of the Stack class, demonstrating stack operations by pushing elements onto the stack, displaying the stack, peeking at the top element without removing it, popping elements from the stack, and displaying the updated stack after popping elements.
Python3
# Creating a stack
stack = Stack()
# Pushing elements onto the stack
stack.push(10)
stack.push(20)
stack.push(30)
# Displaying the stack
stack.display()
# Peeking at the top element
print("Top element:", stack.peek())
# Popping elements from the stack
print("Popped element:", stack.pop())
print("Popped element:", stack.pop())
# Displaying the updated stack
stack.display()
Complete Code Implementation
Below, is the complete code of implementing stack using a linked list in Python.
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def isempty(self):
if self.head == None:
return True
else:
return False
def push(self, data):
if self.head == None:
self.head = Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
# Remove element that is the current head (start of the stack)
def pop(self):
if self.isempty():
return None
else:
poppednode = self.head
self.head = self.head.next
poppednode.next = None
return poppednode.data
# Returns the head node data
def peek(self):
if self.isempty():
return None
else:
return self.head.data
# Prints out the stack
def display(self):
iternode = self.head
if self.isempty():
print("Stack Underflow")
else:
while(iternode != None):
print(iternode.data, end="")
iternode = iternode.next
if(iternode != None):
print(" -> ", end="")
return
# Creating a stack
stack = Stack()
# Pushing elements onto the stack
stack.push(10)
stack.push(20)
stack.push(30)
# Displaying the stack
stack.display()
# Peeking at the top element
print("\nTop element:", stack.peek())
# Popping elements from the stack
print("Popped element:", stack.pop())
print("Popped element:", stack.pop())
# Displaying the updated stack
stack.display()
Output30 -> 20 -> 10
Top element: 30
Popped element: 30
Popped element: 20
10
Time Complexity: O(1), for all push(), pop(), and peek(), as we are not performing any kind of traversal over the list. We perform all the operations through the current pointer only.
Auxiliary Space: O(N), where N is the size of the stack
Similar Reads
Implementation of Stack in Python using List
Stack is a linear data structure that follows the LIFO principle which means Last in First Out. In the stack insertion of a new element and removal of an existing element takes place at the same end represented as the top of the stack. Basic Operations on Stack: push():- This is a method to insert a
4 min read
Python Program to Reverse a linked list
Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> NULLOutput: head: 4 -> 3 -> 2 -> 1 -> NULLExplanation: Reversed Linked List: Input:
3 min read
Implement Stack Using Deque in Python
In Python, Stack, and collections. deque is a foundational data structure used for managing elements in a Last-In-First-Out (LIFO) order. In this article, we will learn to create a stack using collections. deque in Python. Example : Input : Stack : 1 2 4 Push(5)Output : Stack : 1 2 4 5Input : Stack
3 min read
Python Program to Reverse the Content of a File using Stack
Given a file, the task is to change the content in reverse order using Stack, as well as store the lines of that file in reverse order in Python. Examples: Input: 1 2 3 4 5 Output: 5 4 3 2 1 Approach to Python Program to Reverse a Stack Using Recursion Create an empty stack. One by one push every l
2 min read
Python program to find middle of a linked list using one traversal
Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. Method 1: Traverse the whole linked list and count the no. of nodes. Now tra
5 min read
Python3 Program for Clockwise rotation of Linked List
Write a Python3 program for a given singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 1
5 min read
Python Program To Flatten A Multi-Level Linked List Depth Wise- Set 2
We have discussed flattening of a multi-level linked list where nodes have two pointers down and next. In the previous post, we flattened the linked list level-wise. How to flatten a linked list when we always need to process the down pointer before next at every node. Input: 1 - 2 - 3 - 4 | 7 - 8 -
4 min read
Python Program For Reversing A Doubly Linked List
Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
4 min read
Implementation of Deque using Doubly Linked List in Python
A deque (double-ended queue) is a linear data structure that allows insertion and deletion from both the front and rear efficiently. A Doubly Linked List (DLL) is a preferred choice for implementing a deque as it enables O(1) insertion and deletion without shifting elements, unlike lists. Node Struc
3 min read
Python Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read