NC76 用两个栈实现队列

package NC;

import java.util.*;

/**
* NC76 用两个栈实现队列
*
* 用两个栈来实现一个队列,完成 n 次在队列尾部插入整数(push)和在队列头部删除整数(pop)的功能。
* 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
* 要求:空间复杂度 O(n) ,时间复杂度O(1)
* @author Tang
* @date 2021/9/26
*/
public class Queue {
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);
}

public int pop() {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
if(stack2.isEmpty()) {
return 0;
}
return stack2.pop();
}

public static void main(String[] args) {

Queue queue = new Queue();
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());

}

}
posted @ 2021-09-26 20:39  六小扛把子  阅读(70)  评论(0编辑  收藏  举报