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

    笨鸟先飞
  • 相关阅读:
    鬼谷子 简单飞扬
    JavaScript 随笔汇集 简单飞扬
    p2p学习 简单飞扬
    p2p知识 简单飞扬
    使用 JFreeChart来创建基于web的图表 简单飞扬
    Javascript中最常用的55个经典技巧 简单飞扬
    庆祝在博客园申请博客成功
    读《WCF技术剖析》(卷一)笔记(一)
    常用字符串截取类
    创建yum本地源 转帖
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/13913835.html
Copyright © 2020-2023  润新知