用两个堆栈实现一个队列

import java.util.Stack;java

public class Solution {node

Stack<Integer> stack1 = new Stack<Integer>();

Stack<Integer> stack2 = new Stack<Integer>();
//入对列的实现
public void push(int node) {
    //将数据放到堆栈stack1中便可
    stack1.push(node);
	
}
//出对列的实现方法
public int pop() {
    //判断stack1是否为空,不为空,则stack1出栈,放到stack2中
    while(!stack1.isEmpty()){
	
        stack2.push(stack1.pop());
		
    }
	//stack2的栈尾正好是stack1的栈底,取得队列的头一个元素
    int first = stack2.pop();
	//为啥要作这个操做呢,由于若是再有元素进队列,若是不把元素移回去,有元素进入,就不是队列
	//比如作事情,看到成功,还有善后工做
    while(!stack2.isEmpty()){
	
        stack1.push(stack2.pop());
		
    }
	
    return first;
}

}code

相关文章
相关标签/搜索