package lesson01;
import java.util.LinkedList;
import java.util.Queue;
public class Code03_TwoQueueStack {
Queue<Integer> queue;
Queue<Integer> help;
public Code03_TwoQueueStack() {
queue = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
public void push(int item) {
queue.add(item);
}
public int pop() throws Exception {
if (queue.isEmpty()) {
throw new Exception("stack is null!");
}
while (queue.size() > 1) {
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
public int peek() throws Exception {
if (queue.isEmpty()) {
throw new Exception("stack is null!");
}
while (queue.size() > 1) {
help.add(queue.poll());
}
int res = queue.poll();
help.add(res);
swap();
return res;
}
private void swap() {
Queue<Integer> temp;
temp = help;
help = queue;
queue = temp;
}
public static void main(String[] args) throws Exception {
Code03_TwoQueueStack stack = new Code03_TwoQueueStack();
for (int i = 0; i < 7; i++) {
stack.push(i);
}
for (int i = 0; i < 7; i++) {
System.out.print(" " + stack.peek());
stack.pop();
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务