剑指Offer学习 面试题7

//两个栈实现队列


package test7;

import java.util.Stack;

class CQueue {
private Stack stack1=new Stack<>();
private Stack stack2=new Stack<>();
public CQueue(){
}
public  void insertRear(T c){
stack1.add(c);
}
public  T deleteFront(){
if (stack2.isEmpty()) {
if (!stack1.isEmpty()) {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
else {
System.out.println("没有要删除的元素");
return null;
}
}
return stack2.pop();
}
public void print(){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
while(!stack2.isEmpty()){
System.out.print(stack2.pop()+" ");;
}
}
}
public class StackToQueue {
public static void main(String  []args){
CQueue queue =new CQueue();
char c1='a';
char c2='b';
char c3='c';
char c4='d';
char c5='e';
queue.insertRear(c1);
queue.insertRear(c2);
queue.insertRear(c3);
queue.deleteFront();
// queue.print();
queue.insertRear(c4);
queue.insertRear(c5);
// queue.print();
queue.deleteFront();
queue.print();
}
}

你可能感兴趣的:(剑指offer,java,面试题,算法,java学习)