JAVA用双栈实现队列,纪念我挂掉的第一次腾讯面试题

来源:互联网 发布:java thread 回调 编辑:程序博客网 时间:2024/05/18 00:06

import java.util.Stack;

public class Solution {
Stack stack1 = new Stack();
Stack stack2 = new Stack();
int size = 0; //the size of the queue
public void push(int node) {
stack1.push(node); //only push into the stack1
size++; //size++
}

public int pop() {    if(0 == size){                  //if queue is empty, return 0        return 0;    }else{                          //queue is not empty        if(stack2.empty()){         //the stack2 is empty            while(!stack1.empty()){ //push all values of stack1 into stack2                stack2.push(stack1.pop());            }            size--;                 //size--            return stack2.pop();    //pop the value of stack2        }else{            size--;                 //size--            return stack2.pop();    //pop the value from stack2         }    }}

}

0 0