zoukankan      html  css  js  c++  java
  • 【python刷题】栈实现队列

    栈实现队列

    class Queue:
        def __init__(self):
            self.s1 = []
            self.s2 = []
    
        def peek(self):
            if not self.s2:
                while self.s1:
                    self.s2.append(self.s1.pop())
            return self.s2[-1]
    
    
        def push(self, x):
            self.s1.append(x)
    
        def pop(self):
            self.peek()
            if not self.s2:
                return None
            self.s2.pop()
    
        def empty(self):
            return not self.s1 and not self.s2
    
    queue = Queue()
    queue.push(1)
    queue.push(2)
    queue.push(3)
    print("s1:", queue.s1)
    print("s2:", queue.s2)
    t = queue.peek()
    print(t)
    print("s1:", queue.s1)
    print("s2:", queue.s2)
    queue.pop()
    print("s1:", queue.s1)
    print("s2:", queue.s2)
    queue.push(4)
    queue.push(5)
    print("s1:", queue.s1)
    print("s2:", queue.s2)
    queue.pop()
    print("s1:", queue.s1)
    print("s2:", queue.s2)
    t = queue.peek()
    print(t)
    print("s1:", queue.s1)
    print("s2:", queue.s2)
    

    结果:
    s1: [1, 2, 3]
    s2: []
    1
    s1: []
    s2: [3, 2, 1]
    s1: []
    s2: [3, 2]
    s1: [4, 5]
    s2: [3, 2]
    s1: [4, 5]
    s2: [3]
    3
    s1: [4, 5]
    s2: [3]

  • 相关阅读:
    SQL第一讲
    CSS3补充内容
    EXCEL数据导入SQL表的方法
    jq第四讲+实例
    jq第三讲
    jq第二讲
    安卓、苹果日历同步
    安卓、苹果手机备忘录同步
    服务器、客户端双认证
    今天我的博客正式开张了!
  • 原文地址:https://www.cnblogs.com/xiximayou/p/14358667.html
Copyright © 2011-2022 走看看