google.com, pub-4617457846989927, DIRECT, f08c47fec0942fa0 Learn to enjoy every minute of your life.Only I can change my life.: Python program to demonstrate all stack operations using a doubly linked list

Monday, December 16, 2019

Python program to demonstrate all stack operations using a doubly linked list

Write a python program to demonstrate all stack operations using a doubly linked list  :


Answer:

class Node:
 
    def __init__(self, data):
        self.data = data # Assign data
        self.next = None # Initialize next as null
        self.prev = None # Initialize prev as null       
         

class Stack:
    # Function to initialize head 
    def __init__(self):
        self.head = None

    def push(self, data):
 
        if self.head is None:
            self.head = Node(data)
        else:
            new_node = Node(data)
            self.head.prev = new_node
            new_node.next = self.head
            new_node.prev = None
            self.head = new_node
             

    def pop(self):
 
        if self.head is None:
            return None
        else:
            temp = self.head.data
            self.head = self.head.next
            self.head.prev = None
            return temp
 
 

    def top(self):
 
        return self.head.data
 
 

    def size(self):
 
        temp = self.head
        count = 0
        while temp is not None:
            count = count + 1
            temp = temp.next
        return count
           
    def isEmpty(self):
 
        if self.head is None:
           return True
        else:
           return False
             

    def printstack(self):
         
        print("stack elements are:")
        temp = self.head
        while temp is not None:
            print(temp.data, end ="->")
            temp = temp.next         
         
 
       
if __name__=='__main__': 
 

  stack = Stack()
 
  print("Stack operations using Doubly LinkedList")
  stack.push(4)
 

  stack.push(5)
 

  stack.push(6)
 

  stack.push(7)
 
  stack.printstack()
 

  print("\nTop element is ", stack.top())
 

  print("Size of the stack is ", stack.size())
 

  stack.pop()
 

  stack.pop()
   


  stack.printstack()
   

  print("\nstack is empty:", stack.isEmpty())




Output:
Stack operations using Doubly LinkedList
stack elements are:
7->6->5->4->
Top element is  7
Size of the stack is  4
stack elements are:
5->4->
stack is empty: False

No comments:

Post a Comment

हिम्मत

 अंधेरे में एक करोड का हीरा गिर गया था, उसे ढूंढने के लिए पाँच रूपएं की मोमबत्ती ने सहयोग किया। अभी बताओ वह पाँच रूपएं की एक छोटी सी मोमबत्त...