(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());
    }
}

全部评论

相关推荐

牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务