用栈实现队列

2020-05-08  本文已影响0人  大道至简_6a43

package shujujiegou;

import java.util.Stack;

public class stackImplimentQueue {

     Stack  stack1 =new Stack<>();

     Stack  stack2 =new Stack<>();

      public void push(int val) {

      while (!stack2.empty()) {//入栈的时候保证数据都在stack1才能保证入栈的顺序

           stack1.push(stack2.peek());

            stack2.pop();

    }

        stack1.push(val);

        System.out.println("该次入队的值为:" + val);

}

public int pop() {

    while (!stack1.empty()) {//出栈的时候数据都在stack2才能保证出栈的有序性

    stack2.push(stack1.pop());

}

    int tmp =stack2.peek();

    stack2.pop();

    System.out.println("该次出队的值为:" + tmp);

    return tmp;

}

public static void main(String[] args) {

    stackImplimentQueue stackImplimentQueue =new stackImplimentQueue();

    stackImplimentQueue.push(1);

    stackImplimentQueue.push(2);

    stackImplimentQueue.push(3);

    stackImplimentQueue.pop();

    stackImplimentQueue.pop();

    stackImplimentQueue.push(4);

    stackImplimentQueue.pop();

    stackImplimentQueue.pop();

}

}

运行结果为:

该次入队的值为:1

该次入队的值为:2

该次入队的值为:3

该次出队的值为:1

该次出队的值为:2

该次入队的值为:4

该次出队的值为:3

该次出队的值为:4

上一篇下一篇

猜你喜欢

热点阅读