package suanfa;
class CQueue {
public static Stack stack1;
public static Stack stack2;
public CQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
public void appendTail(int value) {
if(stack2.isEmpty() != true){
for(int i = stack2.size()-1;i >= 0 ;i--){
stack1.push(stack2.pop());
}
}
stack1.push(value);
}
public int deleteHead() {
for(int i = stack1.size()-1;i >= 0 ;i--){
stack2.push(stack1.pop());
}
if(stack2.isEmpty()){
return -1;
}
return (Integer)stack2.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
class test {
public static void main(String[] args) {
CQueue cQueue = new CQueue();
System.out.println(cQueue.deleteHead());
cQueue.appendTail(97);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
cQueue.appendTail(15);
System.out.println(cQueue.deleteHead());
cQueue.appendTail(1);
cQueue.appendTail(43);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
cQueue.appendTail(18);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
cQueue.appendTail(36);
cQueue.appendTail(69);
cQueue.appendTail(21);
cQueue.appendTail(91);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
cQueue.appendTail(22);
cQueue.appendTail(40);
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
System.out.println(cQueue.deleteHead());
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
两个栈实现队列
最新推荐文章于 2024-04-22 23:20:09 发布