Complete Code Implementation
Below, is the complete code of implementing stack using a linked list in Python.
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()
Output
30 -> 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
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