一、栈和队列
栈的思想:先进后出,所以在python里用append()和pop()就能实现栈的push压入和pop弹出了。append每次在列表的后面添加一个元素,pop每次弹出列表的最后一个元素,做到了先进后出。
队列的思想:先进先出。
所以要用栈来实现队列的思想如下:
1.如果列表A不为空,假如已经添加元素得到列表A[1,2,3];
2.如果列表B为空,那么就把列表A中的元素从右往左添加进列表B,得到列表B[3,2,1];
3.再对列表B进行pop()操作,即可得到弹出顺序为1,2,3.和最初添加列表A的顺序一致。
二、python实现
class Solution: def __init__(self): self.stack1=[] self.stack2=[] def push(self, node): self.stack1.append(node)#添加元素是从左往右的顺序,如[1,2,3] # write code here def pop(self): if len(self.stack2)==0:#要把元素添加到stack2中,再弹出来 while len(self.stack1)!=0: self.stack2.append(self.stack1[-1])#每次都把stack1中最后一个元素添加,得到[3,2,1] self.stack1.pop()#添加完一个元素后删除 value=self.stack2.pop()#弹出stack2中的后面元素,弹出顺序为[1,2,3]至此变成了先入先出,变成了队列 return value