您的位置:首页 > 其它

用两个栈实现队列&&用两个队列实现一个栈

2016-06-22 00:00 477 查看
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/*
* Q 57 用两个栈实现队列
*/

public class QueueImplementByTwoStacks {

private Stack<Integer> stack1;
private Stack<Integer> stack2;

QueueImplementByTwoStacks(){
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
}

public Integer poll(){
Integer re=null;
if(!stack2.empty()){//如果stack2不为空则弹出栈顶元素
re=stack2.pop();
}else{//如果stack2为空,将stack1中的元素弹出,依次压栈到stack2中,那么stack1栈底的元素就会成为stack2栈顶的元素,从而达到stack1先进先出的队列顺序
while(!stack1.empty()){
re=stack1.pop();
stack2.push(re);
}
if(!stack2.empty()){
re=stack2.pop();
}
}
return re;
}
public Integer offer(int o){//每次只从stack1压栈
stack1.push(o);
return o;
}

public static void main(String[] args) {
QueueImplementByTwoStacks queue=new QueueImplementByTwoStacks();
List<Integer> re=new ArrayList<Integer>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
re.add(queue.poll());
queue.offer(4);
re.add(queue.poll());
queue.offer(5);
re.add(queue.poll());
re.add(queue.poll());
re.add(queue.poll());
System.out.println(re.toString());
}

}

import java.util.LinkedList;

/*
* Q 57 用两个队列实现一个栈
*/
public class StackImplementByTwoQueues {

//use 'queue1' and 'queue2' as a queue.That means only use the method 'addLast' and 'removeFirst'.
private LinkedList<Integer> queue1;
private LinkedList<Integer> queue2;

StackImplementByTwoQueues(){
queue1=new LinkedList<Integer>();
queue2=new LinkedList<Integer>();
}

public Integer pop(){//队列1不为空,队列2为空,将队列顺序读到队列2中,则最后一个元素就是需要弹出的值
Integer re=null;
if(queue1.size()==0&&queue2.size()==0){
return null;
}
if(queue2.size()==0){
while(queue1.size()>0){
re=queue1.removeFirst();//等同re=queue1.remove();
if(queue1.size()!=0){//do not add the last element of queue1 to queue2
queue2.addLast(re);
}
}
}else if (queue1.size()==0){
while(queue2.size()>0){
re=queue2.removeFirst();
if(queue2.size()!=0){//do not add the last element of queue2 to queue1
queue1.addLast(re);
}
}
}
return re;
}
public Integer push(Integer o){
if(queue1.size()==0&&queue2.size()==0){
queue1.addLast(o);//queue2.addLast(o); is also ok
}
if(queue1.size()!=0){
queue1.addLast(o);//等同queue1.=add(0)
}else if(queue2.size()!=0){
queue2.addLast(o);
}
return o;
}

public static void main(String[] args) {
StackImplementByTwoQueues stack=new StackImplementByTwoQueues();
int tmp=0;
stack.push(1);
stack.push(2);
stack.push(3);
tmp=stack.pop();
System.out.println(tmp);//3
stack.push(4);
tmp=stack.pop();
System.out.println(tmp);//4
tmp=stack.pop();
System.out.println(tmp);//2
stack.push(5);
stack.push(6);
tmp=stack.pop();
System.out.println(tmp);//6
tmp=stack.pop();
System.out.println(tmp);//5
tmp=stack.pop();
System.out.println(tmp);//1
7fe8

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: