Implement Queue with Two Stacks

来源:互联网 发布:mpu9250 dmp 9轴算法 编辑:程序博客网 时间:2024/05/16 01:47
class Node {Node next;int data;}class Stack {Node top;boolean isEmpty() {return top == null;}int pop()throws Exception{if(isEmpty()) {throw new Exception("The stack is Empty");}else {int item = top.data;top = top.next;return item;}}void push(int item) {Node node = new Node();node.data =item;node.next = top;top = node;}int peek()throws Exception {if(isEmpty()) {throw new Exception("The stack is empty!");}else {return top.data;}}}class Queue{Stack stackIn = new Stack();Stack stackOut = new Stack();public void enQueue(int element) {stackIn.push(element);}public int deQueue()throws Exception {shift();return stackOut.pop();}public void shift()throws Exception {if(stackOut.isEmpty()) {while(!stackIn.isEmpty()){stackOut.push(stackIn.pop());}}}public int peek()throws Exception {shift();return stackOut.peek();}}

原创粉丝点击