zoukankan      html  css  js  c++  java
  • python堆栈实现

    百度百科定义:
    堆栈是一个在计算机科学中经常使用的抽象数据类型。堆栈中的物体具有一个特性: 最后一个放入堆栈中的物体总是被最先拿出来, 这个特性通常称为后进先出(LIFO)队列。 堆栈中定义了一些操作。 两个最重要的是PUSH和POP。 PUSH操作在堆栈的顶部加入一 个元素。POP操作相反, 在堆栈顶部移去一个元素, 并将堆栈的大小减一。
    我的实现代码如下:

    #-*- coding:utf-8 -*-
    __metaclass__ = type
    
    class mystack():
        def __init__(self,value):
            self.value = value
            self.behind = None
            self.before = None
    
        def __str__(self):
            return str(self.value)
    
    def top(stack):    #顶部
            if isinstance(stack,mystack):
                if stack.behind is not None:
                    return top(stack.behind)
                else:
                    return stack
            else:
                print ('没有初始化')
    
    def push(stack,elem):  #入栈
        in_elem = mystack(elem)
        if isinstance(stack,mystack):
            now_top = top(stack)
            in_elem.before = now_top
            in_elem.before.behind = in_elem
            print ('成功入栈')
        else:
            print ('没有初始化')
    
    def pop(stack):     #出栈
        if isinstance(stack,mystack):
            now_top = top(stack)
            if now_top.before is not None:
                now_top.before.behind = None
                now_top.before = None
                return now_top
            else:
                return('栈空了')
        else:
            return('没有初始化')
    
    demo1 = mystack(1)  #初始化,只能通过demo1访问
    
    for i in range(10): #入栈
        push(demo1,i)
    
    print '---------------'
    print demo1
    
    for p in range(11): #出栈
        print pop(demo1)
    
    输出:
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    成功入栈
    ---------------
    1
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    栈空了
    [Finished in 0.5s]
    
    欢迎来邮件交流:lq65535@163.com
  • 相关阅读:
    双六
    除法取模
    欧拉函数及费马小定理
    基础模运算
    Leeetcode--581. Shortest Unsorted Continuous Subarray
    Codeforces Round #541--1131F. Asya And Kittens(基础并查集)
    leetcode--200. Number of Islands
    leetcode--21. Merge Two Sorted Lists
    leetcode--155. Min Stack
    Codeforces Round #539--1113B
  • 原文地址:https://www.cnblogs.com/lq1024/p/7593641.html
Copyright © 2011-2022 走看看