• 栈的实现


     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()
  • 相关阅读:
    [BZOJ1222/Luogu2224][HNOI2001]产品加工
    [BZOJ1079/Luogu2476][SCOI2008]着色方案
    [BZOJ3098]Hash Killer II
    [BZOJ1818][CQOI2010]内部白点
    [BZOJ1497/Luogu4174][NOI2006]最大获利
    [BZOJ2330/Luogu3275][SCOI2011]糖果
    [BZOJ1208/Luogu2286][HNOI2004]宠物收养场
    [BZOJ1054/Luogu4289][HAOI2008]移动玩具
    Com组件介绍
    webBrowse官方说明
  • 原文地址:https://www.cnblogs.com/cuzz/p/8098182.html
Copyright © 2020-2023  润新知