1. 程式人生 > 實用技巧 >python-實現鏈式棧

python-實現鏈式棧

 7 """                           
  8 用一個類來實現一個節點        
  9 """                           
 10 class Node(object):           
 11     def __init__(self,data):  
 12         self.data = data      
 13         self.next = None      
 14 class linkstack(object):      
 15     def __init__(self):       
 
16 self.top = None 17 def isEmpty(self): 18 return self.top == None 19 def clear(self): 20 self.top = None 21 def length(self): 22 i = 0 23 tempnode =self.top 24 while tempnode is
not None: 25 tempnode = tempnode.next 26 i += 1 27 return i 28 def push(self,item): 29 node = Node(item) 30 node.next = self.top 31 self.top = node 32 def pop(self): 33 self.top = self.top.next
34 def gettop(self): 35 return self.top.data 36 def display(self): 37 if self.top == None: 38 print("None") 39 tempnode = self.top 40 while tempnode is not None: 41 print(tempnode.data,end = " ") 42 tempnode = tempnode.next 43 print() 44 45 if __name__ == "__main__": 46 linkstack1 = linkstack() 47 linkstack1.push(1) 48 linkstack1.push(2) 49 linkstack1.push(3) 50 linkstack1.push(4) 51 linkstack1.push(5) 52 linkstack1.push(6) 53 linkstack1.display() 54 print(linkstack1.gettop()) 55 print(linkstack1.length()) 56 linkstack1.pop() 57 linkstack1.display() 58 linkstack1.clear() 59 linkstack1.display() 60 print(linkstack1.isEmpty())

執行結果

6 5 4 3 2 1
6
6
5 4 3 2 1
None

True
程式碼邏輯較為簡單所以程式碼沒有註釋,如果有什麼地方不明白,歡迎留言!