• 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
    代码逻辑较为简单所以代码没有注释,如果有什么地方不明白,欢迎留言!

    笨鸟先飞
  • 相关阅读:
    [转载]iOS 开发中为什么更新UI都要放在主线程中?
    GCD小结
    多线程的实现
    图片缓存、PathForResource、NSBundle
    IOS全路径和文件名方法、NSBundle
    plist文件
    iphone区别翻新机
    iPhone4S国行、港版、美版、妖机识别与选购(转)
    应用沙盒
    IOS实现新特性功能
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/13913835.html
Copyright © 2020-2023  润新知