Python:插入一个项目到堆栈

问题描述:

我试图插入一个项目到堆栈,但大小仍然是空的输入插入堆栈在这种情况下?Python:插入一个项目到堆栈

加班我得到堆栈的大小/列表是空时

def main_menu(): 
     print('\nMenu:') 
     print('1. Push') 

     the_stack = Stack() 

     while True: 
       try: 
        command = int(input("\nEnter command:")) 
        if command == 1: 
         try: 
          ask = int(input("\nEnter an integer:")) 
          the_stack = Stack() 
          the_stack.push(ask) 
          print("item pushed") 
          print(the_stack.peek()) 

         except ValueError: 
          print ("Enter Integer numbers only") 
       except ValueError: 
        print ('Please input a Number only') 
       else: 
        if 1 <= command < 5: 
         break 
        else: 
         print ('Enter command from 1 to 4 only') 

class Node: 
    """ 
    The Node used for Linked List 
    """ 
    def __init__(self, item, link): 
     self.item = item 
     self.next = link 

class Stack: 

    def push(self, item): 
     self.top = Node(item, self.top) 

if __name__ == '__main__': 
    main_menu() 
    the_stack = Stack() 
+5

Python没有一个内置'Stack'类。你没有发布你的实现,你也错过了一个正确的错误描述。 –

+0

至少你的其他问题有其余的代码在里面......这个没有任何意义。另外,输入没有什么问题,所以请关注你提出的推送逻辑。 –

+0

目前它是因为该物品被推入堆栈,但大小仍然是空的,我不知道为什么 – Kyle

您可以在Python中使用列表作为堆栈: 只是尝试这一个。

the_stack = [] 
    ask = int(input("Enter an integer:")) 
    the_stack.append(ask) 
    print("Item Added") 

只要你想这个只要使用for循环,你可以添加尽可能多的项目。 从中删除一个项目。 使用

the_stack.pop() 

它会从您的列表中删除最后添加的项目。

Python中没有任何Stack方法。

但您可以使用列表作为堆栈。请参考以下链接 -

https://docs.python.org/2/tutorial/datastructures.html#using-lists-as-stacks