1.栈(stacks)是一种只能经过访问其一端来实现数据存储与检索的线性数据结构,具备后进先出(last in first out,LIFO)的特征node
2.队列(queue)是一种具备先进先出特征的线性数据结构,元素的增长只能在一端进行,元素的删除只能在另外一端进行。可以增长元素的队列一端称为队尾,能够删除元素的队列一端则称为队首。数据结构
stack = [3, 4, 5] stack.append(2) stack.append(6) print(stack) stack.pop() print(stack) stack.pop() print(stack)
[3, 4, 5, 2, 6] [3, 4, 5, 2] [3, 4, 5]
from collections import deque queue = deque(["Eric", "John", "Michael"]) print(queue) queue.append("Terry") # Terry arrives queue.append("Graham") # Graham arrives print(queue) queue.popleft() # The first to arrive now leaves queue.popleft() # The second to arrive now leaves deque(['Michael', 'Terry', 'Graham']) print(queue)
deque(['Eric', 'John', 'Michael']) deque(['Eric', 'John', 'Michael', 'Terry', 'Graham']) deque(['Michael', 'Terry', 'Graham'])
建立两个栈stack1和stack2,使用两个“先进后出”的栈实现一个“先进先出”的队列。app
咱们经过一个具体的例子分析往该队列插入和删除元素的过程。首先插入一个元素a,不妨先把它插入到stack1,此时stack1中的元素有{a},stack2为空。再压入两个元素b和c,仍是插入到stack1中,此时stack1的元素有{a,b,c},其中c位于栈顶,而stack2仍然是空的。code
这个时候咱们试着从队列中删除一个元素。按照先入先出的规则,因为a比b、c先插入队列中,最早删除的元素应该是a。元素a存储在stack1中,但并不在栈顶,所以不能直接进行删除操做。注意stack2咱们一直没有使用过,如今是让stack2发挥做用的时候了。若是咱们把stack1中的元素逐个弹出压入stack2,元素在stack2中的顺序正好和原来在stack1中的顺序相反。所以通过3次弹出stack1和要入stack2操做以后,stack1为空,而stack2中的元素是{c,b,a},这个时候就能够弹出stack2的栈顶a了。此时的stack1为空,而stack2的元素为{b,a},其中b在栈顶。队列
所以咱们的思路是:当stack2中不为空时,在stack2中的栈顶元素是最早进入队列的元素,能够弹出。若是stack2为空时,咱们把stack1中的元素逐个弹出并压入stack2。因为先进入队列的元素被压倒stack1的栈底,通过弹出和压入以后就处于stack2的栈顶,有能够直接弹出。若是有新元素d插入,咱们直接把它压入stack1便可。it
class Solution: def __init__(self): self.stack1 = [] self.stack2 = [] self.result = [] def push(self, node): # write code here self.stack1.append(node) self.result = self.stack1 + self.stack2 def pop(self): # return xx if len(self.stack2) == 0: while self.stack1: self.stack2.append(self.stack1.pop()) self.result = self.stack2 return self.stack2.pop() a = Solution() a.push(1) a.push(2) a.push(3) a.push(4) print(a.result) a.pop() print(a.result) a.pop() print(a.result)
[1, 2, 3, 4] [4, 3, 2] [4, 3]