1、如何仅用队列结构实现栈
import java.util.LinkedList;
import java.util.Queue;
public class e3_StackQueue {
private Queue<Integer> data;
private Queue<Integer> help;
public e3_StackQueue(){
data=new LinkedList<Integer>();
help=new LinkedList<Integer>();
}
public void push(Integer obj){
data.add(obj);
}
public Integer pop(){
if (data.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Queue is empty");
}
while (data.size()>1){
help.add(data.poll());
}
Integer tem = data.poll();
swap();
return tem;
}
public Integer peek(){
if (data.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Queue is empty");
}
while (data.size()>1){
help.add(data.poll());
}
Integer tem=data.peek();
help.add(data.poll());
swap();
return tem;
}
public void swap(){
Queue<Integer> tem=data;
data=help;
help=tem;
}
public static void main(String[] args) {
e3_StackQueue s=new e3_StackQueue();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
System.out.println(s.data);
System.out.println("栈的peek操作:");
System.out.println(s.peek());
System.out.println("栈的pop操作,pop两次");
System.out.println(s.pop());
System.out.println(s.pop());
}
}
2、如何仅用栈结构实现队列
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class e4_StackQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
public e4_StackQueue(){
pushStack=new Stack<Integer>();
popStack=new Stack<Integer>();
}
public void push(Integer obj){
pushStack.push(obj);
}
public Integer pop(){
if (popStack.isEmpty()&&pushStack.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Queue is empty1");
}
pouraway();
return popStack.pop();
}
public Integer peek(){
if (!popStack.isEmpty()){
throw new ArrayIndexOutOfBoundsException("Queue is empty2");
}
pouraway();
return popStack.peek();
}
public void pouraway(){
if (!popStack.isEmpty()){
return;
}
while (!pushStack.isEmpty()){
popStack.push(pushStack.pop());
}
}
public static void main(String[] args) {
e4_StackQueue q=new e4_StackQueue();
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
System.out.println(q.pushStack);
System.out.println("队列的peek操作:");
System.out.println(q.peek());
System.out.println("队列的poll操作,poll两次");
System.out.println(q.pop());
System.out.println(q.pop());
}
}