package offer;
import java.util.Stack;
public class Queue_rec {
private Stack<Integer> stack;
public Queue_rec(){
this.stack=new Stack<Integer>();
}
public void add(int newNum){
this.stack.push(newNum);
}
public boolean empty(){
return this.stack.empty();
}
public int poll(){
if(this.stack.empty()){
throw new RuntimeException("Your queue is empty!");
}
int result=this.stack.pop();
if(this.stack.empty()){
return result;
}else{
int last=this.poll();
this.stack.push(result);
return last;
}
}
public int peek(){
if(this.stack.empty()){
throw new RuntimeException("Your queue is empty!");
}
int result=this.stack.pop();
if(this.stack.empty()){
this.stack.push(result);
return result;
}else{
int last=this.peek();
this.stack.push(result);
return last;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue_rec q=new Queue_rec();
q.add(1);
q.add(5);
q.add(6);
q.add(9);
//System.out.println(q.peek());
//System.out.println(q.peek());
while(!q.empty()){
System.out.println(q.poll());
}
}
}
Java: 栈+递归实现队列功能和操作(add,poll,peek)
最新推荐文章于 2022-07-21 17:46:18 发布