In: Computer Science
Write a code to implement a python stack class using linked list. use these operations
isEmpty • push. • pop. • peek. • size
Time and compare the performances ( this is optional but I would appreciate it)
# Node structure
class Node:
def __init__(self, key, next=None):
self.key = key
self.next = next
# Main Stack structure
class Stack:
def __init__(self):
self.top = None
self.count = 0
# Utility function to add an element x in the stack
def push(self, x): # insert at the beginning
# Allocate the new node in the heap
node = Node(x)
# check if stack is full. Then inserting an element would
# lead to stack overflow
if node is None:
print("Stack Overflow")
return
print("Pushing", x)
# set the data in allocated node
node.data = x
# Set the .next pointer of the new node to point to the current
# top node of the list
node.next = self.top
# update top pointer
self.top = node
self.count+=1
def size(self):
print("size of the current Stack is",self.count)
# Utility function to check if the stack is empty or not
def isEmpty(self):
return self.top is None
# Utility function to return top element in a stack
def peek(self):
# check for empty stack
if not self.isEmpty():
return self.top.data
else:
print("Stack is empty")
return -1
# Utility function to pop top element from the stack
def pop(self): # remove at the beginning
# check for stack underflow
if self.top is None:
print("Stack Underflow")
return
print("Poping", self.peek())
# update the top pointer to point to the next node
self.top = self.top.next
self.count-=1
if __name__ == '__main__':
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.size()
print("Top element is", stack.peek())
stack.pop()
stack.size()
stack.pop()
stack.pop()
if stack.isEmpty():
print("Stack is empty")
else:
print("Stack is not empty")