首页 > 学院 > 开发设计 > 正文

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

2019-11-06 08:22:44
字体:
来源:转载
供稿:网友

主要思路是,一个stack1占用来接收正常的压栈,一个stack2用来存放stack1的倒序,当执行pop()操作时,弹出的是stack2的栈顶元素,就会有“先进先出的效果”。

import java.util.Stack;public class Solution {	Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();        public void push(int node) {        while(!stack2.isEmpty()){        	stack1.push(stack2.pop());        }        stack1.push(node);        while(!stack1.isEmpty()){        	stack2.push(stack1.pop());        }    }        public int pop() {        return stack2.pop();    }	public static void main(String[] args) {		// TODO Auto-generated method stub        Solution s = new Solution();        s.push(1);        s.push(2);        s.push(3);        s.push(4);        s.push(5);        System.out.PRintln(s.pop()); 	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表