两个栈实现队列:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
两个队列实现栈:
package com.www.swordofoffer;
import java.util.LinkedList;
public class QueuesToStack
{
Queue<Integer> queue1=new LinkedList<Integer>();
Queue<Integer> queue2=new LinkedList<Integer>();
public void push1(int value){
queue1.add(value);
}
//方法:出栈操作
public int pop2() throws Exception {
int data;
if (queue1.size() == 0) {
throw new Exception("栈为空");
}
while (queue1.size() != 0) {
if (queue1.size() == 1) {
data = queue1.poll();
while (queue2.size() != 0) { //把queue2中的全部数据放到队列一中
queue1.add(queue2.poll());
}
return data;
}
queue2.add(queue1.poll());
}
throw new Exception("栈为空");//不知道这一行的代码是什么意思
}
LinkedList<Integer> queue1=new LinkedList<Integer>();
LinkedList<Integer> queue2=new LinkedList<Integer>();
public void push(int value)//入栈
{
queue1.addLast(value);
}
public int pop()//出栈 必须是非空的栈才能出栈啊
{
if(sSize()!=0)//栈不为空
{
//移动一个队的n-1个到另一个中
if(!queue1.isEmpty())//q1 不为空
{
putN_1ToAnthor();
return queue1.removeFirst();
}
else //q2 不为空
{
putN_1ToAnthor();
return queue2.removeFirst();
}
}
else
{
System.out.println("栈已经为空啦,不能出栈");
return -1;
}
}
public int sSize()
{
return queue1.size()+queue2.size();
}
public void putN_1ToAnthor()//从非空中出队n-1个到另一个队列 因为队列总是一空一非空
{
if(!queue1.isEmpty())
{
while(queue1.size()>1)
{
queue2.addLast(queue1.removeFirst());
}
}
else if(!queue2.isEmpty())
{
while(queue2.size()>1)
{
queue1.addLast(queue2.removeFirst());
}
}
}
public static void main(String[] args)
{
QueuesToStack stack=new QueuesToStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(5);
stack.push(6);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}