Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Missed Print Line

I am trying to print the program so it will look like this.


Inserting 1
Inserting 2
Inserting 3
Top element is 3
Removing 3
Removing 2
Removing 1
The stack is empty


But when I run the program, I missed "Inserting 1".
My code look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
            print("Inserting ", str(self.head.data))
    
    def pop(self):
        if self.isempty():
            return None
        else:
            poppednode = self.head
            self.head = self.head.next
            poppednode.next = None
            print("Removing",poppednode.data)
            return poppednode.data

    def peek(self):
        if self.isempty():
            return None
        else:
            return self.head.data

    def display(self):
        iternode = self.head
        if self.isempty():
            print("The stack is empty")
        else:
            while(iternode != None):
                print(iternode.data,"->",end = "")
                iternode = iternode.next
            return
        
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)

print("Top element is ",stack.peek())

stack.pop()
stack.pop()
stack.pop()
stack.display()

>Solution :

First time you push an item, self.head is None so the first block of code is executed. Unindent the print(‘Insert’) line so it prints for both cases.

    def push(self,data):
        if self.head == None:
            self.head = Node(data)
        else:
            newnode = Node(data)
            newnode.next = self.head
            self.head = newnode
        print("Inserting ", str(self.head.data)) # <== unindent 1-level
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading