Implement stack using linked list

Table of Contents

Implement stack using linked list

This program will help students to understand the concepts of stack and linked list and their working. We have implemented stack using inked list. We have performed following operations of stack using linked list.

  • Push
  • Pop
  • Seek
  • Length

Please check our other stack programs

class Node:
    
    def __init__(self, data):
        self.data = data
        self.next = None
class StackLinkedList:
    # Author : ITVoyagers Website : itvoyagers.in
    def __init__(self):
        self.top = None
        self.size=0
        self.items=None
# Author : ITVoyagers Website : itvoyagers.in
    #Returns  True  if  the  stack  is  empty  or  False  otherwise.
    def  isEmpty(  self  ):
        if(self.size==0):
            return True
        else:
            return False
    # Returns  the  number  of  items  in  the  stack.
    def	length (  self  ):
        if self.isEmpty():
            print("Stack is empty")
        else:
            print("number of items present is list are",self.size)
            # Author : ITVoyagers Website : itvoyagers.in
    # Returns  the  top  item  on  the  stack  without  removing  it.
    def  peek(  self  ):
        if self.isEmpty():
            print("Stack is empty")
        else:
            print("top most element is", self.top.data)
# Author : ITVoyagers Website : itvoyagers.in
    # Removes  and  returns  the  top  item  on  the  stack.
    def  pop(  self  ):
        if  self.isEmpty():
            print("Stack is empty")
        else:
            value=self.top.data
            self.top=self.top.next
            #print("the poped elememt is ", self.items.pop())
            self.size-=1
            print("popped element is ", value)
    # Push  an  item  onto  the  top  of  the  stack.
    def  push(  self,  item  ):
        n1=Node(item)
        n1.next=self.top
        self.top=n1
        self.size+=1
s=StackLinkedList()
# Author : ITVoyagers Website : itvoyagers.in
print("Menu")
print("1.push n2.pop n3.peek n4.length")
ch=int(input("Enter your choice"))
while ch<=4:
    if(ch==1):
        value=int(input("Enter value to be inserted"))
        s.push(value)
    elif (ch==2):
        s.pop()
    elif (ch==3):
        s.peek()
    elif (ch==4):
        s.length()
    ch=int(input("Enter your choice"))
# Author : ITVoyagers Website : itvoyagers.in

Output :

Menu
1.push 
2.pop 
3.peek 
4.length
Enter your choice1
Enter value to be inserted100
Enter your choice1
Enter value to be inserted200
Enter your choice1
Enter value to be inserted300
Enter your choice2
popped element is  300
Enter your choice3
top most element is 200
Enter your choice4
number of items present is list are 2
Enter your choice

Note : Please note that above program is compatible with Python 3 or higher version.

Leave a Comment