2016-04-27 109 views
-4

我試圖插入一個項目到堆棧,但大小仍然是空的輸入插入堆棧在這種情況下?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

回答

0

您可以在Python中使用列表作爲堆棧: 只是嘗試這一個。

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

只要你想這個只要使用for循環,你可以添加儘可能多的項目。 從中刪除一個項目。 使用

the_stack.pop() 

它會從您的列表中刪除最後添加的項目。