• 【DataStructure In Python】Python模拟栈和队列


    用Python模拟栈和队列主要是利用List,当然也可以使用collection的deque。
    以下内容为栈:

    #! /usr/bin/env python
    # DataStructure Stack
    
    class Stack:
    
        def __init__(self, data=None):
            if data is not None:    
                self.stk = [data]
                self.top = 0
            else:
                self.stk = []
                self.top = -1
    
        def __str__(self):
            return " ".join([str(x) for x in self.stk])
                        
        def push(self, data):
            self.stk.append(data)
            self.top += 1
        
        def pop(self):
            if self.top == -1:
                print "Stack is empty"
                return 
            return self.stk.pop()
        
        def isEmpty(self):
            if self.top == -1:
                return 1
            else :
                return 0
    
    if __name__ == "__main__":
        stack = Stack()
        for i in range(10):
            stack.push(i)
        print "push:",stack
        print "pop: ",
        for i in range(3):
            print stack.pop(),
        print ""
        print "left:",stack

    以下内容为队列:

    #! /usr/bin/env python
    # DataStructure Queue
    
    class Queue:
        
        def __init__(self, data=None):
            if data is not None:
                self.que = [data]
            else:
                self.que = []
    
        def __str__(self):
            return " ".join([str(x) for x in self.que])
    
        def isEmpty(self):
            if len(self.que):
                return 0
            else:
                return 1
    
        def enQueue(self, data):
            self.que.append(data)
    
        def deQueue(self):
            return self.que.pop(0)
    
    if __name__ == "__main__":
        queue = Queue()
        for i in range(10, 0, -1):
            queue.enQueue(i)
        print "enQueue:",queue
        print "deQueue:",
        for i in range(3):
            print queue.deQueue(),
        print ""
        print "left:   ",queue
  • 相关阅读:
    免费获取pptv会员
    LNMP环境包安装IonCube教程
    linux系统lnmp环境包搬家教程
    进入网站自动加自己为QQ好友代码
    vip视频解析接口
    CF使用TGP下载后,分卷文件损坏的解决方法
    体育赛事
    浅谈thinkphp中将字符串转换成json数组的方法
    android ANR问题
    android 单例模式
  • 原文地址:https://www.cnblogs.com/bombe1013/p/3587772.html
Copyright © 2020-2023  润新知