用两个栈实现队列

来源:互联网 发布:sql2000数据库卸载 编辑:程序博客网 时间:2024/06/07 23:26

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

/***思路:入队直接用stack1存储,出队需要满足先进先出,因此需要再用一个*stack2将stack1中的内容输出*/Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node){        stack1.push(node);    }    public int pop(){        if(stack1.isEmpty()&&stack2.isEmpty())            throw new RuntimeException("Queue is empty");        if(stack2.isEmpty()){            while(!stack1.isEmpty()){                stack2.push(stack1.pop());            }        }        return stack2.pop();    }

包含测试用例的完整代码如下:

package stackAndQue;import java.util.Stack;/** * 用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型 * @author NST_Xx * 思路: */public class Solution {    public static void main(String[] args) {        Solution s = new Solution();        s.push(1);        s.push(2);        s.push(3);        s.push(4);        s.pop();    }    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node){        stack1.push(node);    }    public int pop(){        if(stack1.isEmpty()&&stack2.isEmpty())            throw new RuntimeException("Queue is empty");        if(stack2.isEmpty()){            while(!stack1.isEmpty()){                stack2.push(stack1.pop());            }        }        return stack2.pop();    }}

结果:
1
总结:这道题考察栈和队列的性质。

0 0
原创粉丝点击