(5)两个栈实现队列

1.问题

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

2.思路


(1)加入的数据都放入stack1中
(2)取数据时,如果stack2中有数据就直接stack2.pop()取走数据,如果stack2中没有数据,就将stack1中的数据全部加入到stack2中以后再从stack2中取数据。

3.代码

package test1_10;

import java.util.Stack;

 /* * @author qianliu on 2019/4/8 14:58 * @Discription: * 1.题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 */
public class Test5 {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    /* * @author qianliu on 2019/4/8 14:34 * @param [node] * @return void * @Discription:将数据加入到stack1中 */
    public void push(int node) {
        stack1.push(node);
    }

    /* * @author qianliu on 2019/4/8 14:53 * @param [] * @return int * @Discription:取数据时,如果stack2中有数据就直接stack2.pop()取走数据, * 如果stack2中没有数据,就将stack1中的数据全部加入到stack2中以后再从stack2中取数据。 */
    public int pop() {

        //把stack1中的数据转移到stack2
        if(stack2.empty()){//没有数据
            while (!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }

        //返回stack2中的数据
        return stack2.pop();
    }

    public static void main(String[] args) {
        Test5 test5 = new Test5();
        test5.push(1);
        test5.push(2);
        test5.push(3);
        System.out.println(test5.pop());
        test5.push(4);
        System.out.println(test5.pop());
        System.out.println(test5.pop());
        System.out.println(test5.pop());
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务