zoukankan      html  css  js  c++  java
  • 栈的实现

     1 # -*- coding:utf-8 -*-
     2 """
     3 数据结构的核心是,一个结构只有特定的操作, 可以实现特定的功能
     4 栈的特点是 先进先出 , 一般有这几个操作
     5 push 将一个元素存入栈中
     6 pop 将一个元素从栈中取出, 并在栈中删除他
     7 
     8 top 将一个元素从栈中取出
     9 is_empty 查看栈是否为空
    10 """
    11 
    12 
    13 # Node 类是一个节点, 有两个属性, 一个储存元素,一个储存指向另一个节点的引用
    14 class Node(object):
    15     def __init__(self, element=None, next=None):
    16         self.element = element
    17         self.next = next
    18 
    19     # 这个函数会在print的时候自动调用, 就是把Node显示出来
    20     def __repr__(self):
    21         return str(self.element)
    22 
    23 
    24 class Stack(object):
    25     # 初始化函数, 自动被调用
    26     # 初始化Stack()类的时候, 他有一个head的属性, 值是一个空的Node
    27     def __init__(self):
    28         self.head = Node()
    29 
    30     # 如果head的next的属性为空, 说明栈为空
    31     def is_empty(self):
    32         return self.head.next is None
    33 
    34     # 这样不行, 最后找不到head
    35     # # 创建一个node,
    36     # def push(self,element):
    37     #     n = Node(element)
    38     #     self.head.next = n
    39     #     self.head = n
    40 
    41     # 创建一个node, 并让他指向当前的head.next指向的元素, 在把head.next指向他
    42     def push(self, element):
    43         n = Node(element, self.head.next)
    44         self.head.next = n
    45 
    46     def pop(self):
    47         n = self.head.next
    48         if not self.is_empty():
    49             self.head.next = n.next
    50         return n
    51 
    52 
    53 def test():
    54     s = Stack()
    55     s.push(1)
    56 
    57     print(s.pop())
    58     s.push(2)
    59     s.push(3)
    60     s.push(4)
    61     s.push(5)
    62     print(s.pop())
    63     print(s.pop())
    64     print(s.pop())
    65     print(s.pop())
    66 
    67 
    68 if __name__ == "__main__":
    69     test()
  • 相关阅读:
    【python】元组
    【python】列表
    1-读书的网站
    35-Python
    34-TypeError: BoxSizer.AddSpacer(): argument 1 has unexpected type 'tuple'
    33-wxpython多个frame之间的信息共享
    32-python代码打包成exe文件-pyinstaller
    31-字符串转为 url 格式的两种不同情况
    30-python3 中 bytes 和 string 之间的互相转换
    9-eclispe中右键BuildPath没有了
  • 原文地址:https://www.cnblogs.com/cuzz/p/8098182.html
Copyright © 2011-2022 走看看