漏印行
Missed Print Line
我正在尝试打印程序,因此它看起来像这样。
插入 1
插入 2
插入 3
顶部元素是 3
删除 3
删除 2
删除 1
堆栈为空
但是当我运行程序时,我错过了“插入1”。
我的代码看起来像这样
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()
当你第一次按下时 self.head 将是 None 并且它不会进入打印“插入 1”的其他条件
第一次推送项目时,self.head 是 None,所以第一个代码块被执行。取消缩进 print('Insert') 行,以便在两种情况下打印。
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
我正在尝试打印程序,因此它看起来像这样。
插入 1
插入 2
插入 3
顶部元素是 3
删除 3
删除 2
删除 1
堆栈为空
但是当我运行程序时,我错过了“插入1”。 我的代码看起来像这样
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()
当你第一次按下时 self.head 将是 None 并且它不会进入打印“插入 1”的其他条件
第一次推送项目时,self.head 是 None,所以第一个代码块被执行。取消缩进 print('Insert') 行,以便在两种情况下打印。
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