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.
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.
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.
# 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()
Python Program to Implement Stack Using Linked List
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