Home > Software engineering >  Missed Print Line
Missed Print Line

Time:04-10

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

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()

CodePudding user response:

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

CodePudding user response:

When you are pushing the first time self.head will be None and it won't go in the else condition where it is printing "Inserting 1"

  • Related