兩個棧實現隊列
採用兩個棧,一個push棧,一個pop棧,每次只有當push的時候直接進push棧,每次pop的時候,只要只從pop棧中彈出,在pop棧爲null的時候,將push棧中的所有元素壓棧到pop棧中,這樣就還原了元素添加的順序,先進先出,注意,只有在pop棧爲null的時候才能壓棧,如果不是會亂序,不會達到先進先出的目的。舉例:
- push棧添加1,2,3,4,5。
- 現在需要進行pop操作,那麼在保證pop棧爲null的情況下將pop棧中的所有元素彈出添加到pop棧,彈出順序爲5,4,3,2,1,那麼pop棧添加元素的順序也爲5,4,3,2,1,接着直接將棧頂元素1彈出,符合先進先出。
class TwoStackQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
TwoStackQueue() {
pushStack = new Stack<>();
popStack = new Stack<>();
}
public void push(int num) {
pushStack.push(num);
}
public int pop() {
if (pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
// 如果popStack爲空,那麼就將pushStack中的元素全部壓入到popStack
if (popStack.isEmpty()) {
while ( !pushStack.isEmpty() ) {
popStack.push(pushStack.pop());
}
}
// 返回popStack的棧頂元素
return popStack.pop();
}
public int peek(){
if (pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
if (popStack.isEmpty()) {
while ( !pushStack.isEmpty() ) {
popStack.push(pushStack.pop());
}
}
return popStack.peek();
}
}
兩個隊列實現棧
採用兩個棧,一個queue,一個help,每次push的時候直接進queue隊列,在pop的時候,直接將queue中的元素poll()到只剩一個元素,將剩下的一個元素poll()掉就行,而剩下的元素都add到help隊列中,注意,每次pop或者peek後必須將兩個隊列的索引交換。舉例:
- push了1,2,3,4,5到queue
- pop操作:隊列queue依次彈出再添加到help隊列,1,2,3,4 現在help元素爲1,2,3,4,接着講queue中剩下唯一一個元素5彈出,符合後進先出。
- swap()交換queue和help索引,這樣有新的元素來就可以繼續添加。
class TwoQueueStack {
private Queue<Integer> queue;
private Queue<Integer> help;
TwoQueueStack(){
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(int num) {
queue.add(num);
}
public int pop(){
if (queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while ( queue.size() > 1 ) {
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
public int peek(){
if (queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while ( queue.size() > 1 ) {
help.add(queue.poll());
}
int res = queue.poll();
help.add(res);
swap();
return res;
}
private void swap() {
Queue<Integer> tmp = help;
help = queue;
queue = tmp;
}
}