如何仅用队列实现一个栈?如何仅用栈实现一个队列?

这是一个简单的问题,但要是思维被限制了,就很难搞得定。大体的思路就是利用队列先进先出的特点来实现一个栈,将队列1的元素倒入队列2中,将最后一个元素返回就是了。实现队列也是同样的道理。

/**
* 利用两个队列实现一个栈
* 功能:push,pop,peek
*/

import java.util.LinkedList;
import java.util.Queue;
public class C04_QueueToStack {
public static class MyStack{
private Queue<Integer>queue1;
private Queue<Integer>queue2;
public MyStack(){
//Queue是一个接口,new 它的实现类
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
//压栈
public void push(int num){
queue1.add(num);
}
//弹栈
public int pop(){
if(queue1.isEmpty()){
throw new RuntimeException("the stack is empty!");
}
//队列1的数全部压进队列2
while(queue1.size()!=1){
queue2.add(queue1.poll());
}
int res= queue1.poll();//res 记录最后一个元素
swap();
return res;
}
//查看栈
public int peek(){
if(queue1.isEmpty()){
throw new RuntimeException("the stack is empty!");
}
//队列1的数全部压进队列2
while(queue1.size()!=1){
queue2.add(queue1.poll());
}
int res = queue1.poll();
queue2.add(res);
swap();
return res;
}
public boolean isEmpty(){
return queue1.isEmpty();
}
//交换一下指针
private void swap(){
Queue<Integer>queue = queue1;
queue1 = queue2;
queue2 = queue;
}
}
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(3);
myStack.push(6);
myStack.push(9);
System.out.println(myStack.peek()+"====");
while(!myStack.isEmpty()){
System.out.println(myStack.pop());
}
}
}


/**
* 利用两个栈实现一个队列
* 栈先进后出,队列先进先出
* 实现:push,pull,peek
*/
import java.util.Stack;
public class C03_StackToQueue {
public static class MyQueue{
private Stack<Integer>stack1;
private Stack<Integer>stack2;
public MyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
// 进队列就压在stack1
public void push(int num){
stack1.push(num);
}
//出队列
public int pull(){
if(stack1.isEmpty()){
throw new RuntimeException("the queue is empty!");
}
//stack1全部压进stack2
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int res = stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return res;
}
//查询队列
public int peek(){
if(stack1.isEmpty()){
throw new RuntimeException("the queue is empty!");
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int res = stack2.peek();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return res;
}
public boolean isEmpty(){
return stack1.isEmpty();
}
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(2);
myQueue.push(4);
myQueue.push(7);
System.out.println(myQueue.peek()+"====");
while(!myQueue.isEmpty()){
System.out.println(myQueue.pull());
}
}
}