@
解题思路
栈的特征是“LIFO”,即先进后出,队列的特征是“FIFO”,即先进先出,那么就可以使用 两个栈s1和s2来实现队列,例如有数据顺序为a,b,c,d,先把数据push进s1,这个时候如果想要删除数据,只能删除d,这不符合队列的“头删”特性 ,因此要把s1的数据逐个pop出来,push进s2,这个时候再删除数据的话,就是先删除a,从而实现“头删”功能。
栈的另一个特性就是“尾插”,这里就直接在s1里插入,不过这里有一个前提就是要把s2中的数据全部pop出再push进s1,这样效率有点低,不过也是一种方法。
java实现
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
int first = stack2.pop();
while(!stack2.isEmpty())
{
stack1.push(stack2.pop());
}
return first;
}
}
python 实现
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1=[]
self.stack2=[]
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
if self.stack2==[]:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
return self.stack2.pop()