zoukankan      html  css  js  c++  java
  • 040 两个队列生成一个栈

    想要实现两个队列生成一个栈,需要先了解队列和栈的特性:

    • 队列,先进先出。
    • 栈,后进先出。

    使用两个队列生成一个栈的实现思路为:

    代码实现如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import queue
     
     
    class Stack(object):
     
        def __init__(self):
            self.master_queue = queue.Queue()
            self.minor_queue = queue.Queue()
     
        def push(self, value):
            """
            入栈
            :param value:
            :return:
            """
            self.master_queue.put(value)
     
        def pop(self):
            """
            出栈
            :return:
            """
            if self.master_queue.qsize() == 0:
                return None
     
            while True:
                if self.master_queue.qsize() == 1:
                    value = self.master_queue.get()
                    break
                self.minor_queue.put(self.master_queue.get())
     
            self.master_queue, self.minor_queue = self.minor_queue, self.master_queue
     
            return value
     
     
    obj = Stack()
    obj.push('武沛齐')
    obj.push('Alex')
    obj.push('肖峰')
     
    print(obj.pop())
    print(obj.pop())
    print(obj.pop())

      

  • 相关阅读:
    .net百度编辑器的使用
    phpstudy远程连接mysql
    HDU-2389 Rain on your Parade
    HDU-2768 Cat vs. Dog
    HDU-1151 Air Raid
    HDU-1507 Uncle Tom's Inherited Land*
    HDU-1528/1962 Card Game Cheater
    HDU-3360 National Treasures
    HDU-2413 Against Mammoths
    HDU-1045 Fire Net
  • 原文地址:https://www.cnblogs.com/abdm-989/p/14214035.html
Copyright © 2011-2022 走看看