zoukankan      html  css  js  c++  java
  • 用两个栈实现队列与用两个队列实现栈(Python实现)

    用两个栈实现队列:

     1 class QueueWithTwoStacks(object):
     2     def __init__(self):
     3         self._stack1 = []
     4         self._stack2 = []
     5 
     6     def appendTail(self,x):
     7         self._stack1.append(x)
     8 
     9     def deleteHead(self):
    10          if self._stack2:
    11              return self._stack2.pop()
    12          else:
    13              if self._stack1:
    14                 while self._stack1:
    15                     self._stack2.append(self._stack1.pop())
    16                 return self._stack2.pop()
    17              else:
    18                  return None

    用两个队列实现栈:

     1 class StackWithTwoQueues(object):
     2     def __init__(self):
     3         self._stack1 = []
     4         self._stack2 = []
     5 
     6     def push(self,x):
     7         if len(self._stack1) == 0:
     8             self._stack1.append(x)
     9         elif len(self._stack2) == 0:
    10             self._stack2.append(x)
    11         if len(self._stack2) == 1 and len(self._stack1) >= 1:
    12             while self._stack1:
    13                 self._stack2.append(self._stack1.pop(0))
    14         elif len(self._stack1) == 1 and len(self._stack2) > 1:
    15             while self._stack2:
    16                 self._stack1.append(self._stack2.pop(0))
    17 
    18     def pop(self):
    19         if self._stack1:
    20             return self._stack1.pop(0)
    21         elif self._stack2:
    22             return self._stack2.pop(0)
    23         else:
    24             return None
  • 相关阅读:
    python3.5过滤网址和图片的函数自己亲测可用
    关于接口数据编写的思路整理
    Mysql db
    在Maven中设置Nexus私有服务为中央工厂
    maven 镜像使用
    maven 自建库
    Windows批处理(cmd/bat)常用命令小结
    springmvc and maven
    spring 源码解析
    spring aop 原理
  • 原文地址:https://www.cnblogs.com/hwf-73/p/7705100.html
Copyright © 2011-2022 走看看