0
点赞
收藏
分享

微信扫一扫

Java通过栈实现队列,队列实现栈


如何仅用队列结构实现栈结构?

         1、准备两个队列:data和help

         2、假设往data中push数据1、2、3、4、5,当需要poll出5时,先将1、2、3、4 add进help队列中,                                                       在将data中的5 poll出来返回

         3、然后执行swap,交换data个help性质

         4、当需要pop出4时,步骤和2、3基本一致

如何仅用栈结构实现队列结构?

         1、准备两个栈:stackPush和stackPop

         2、假设往栈stackPush中push进五个数:1、2、3、4、5,然后需要pop出1时,先将stackPush中所有数据

               全部add到stackPop中,然后stackPop通过pop出1返回

         3、需要pop出2时,操作步骤与2基本一致

代码如下:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class StackAndQueueConvert_03 {

//两个栈实现队列结构
public static class TwoStacksQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;

public TwoStacksQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}

public void push(int pushInt) {
stackPush.push(pushInt);
}

public int poll() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
} else if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}

public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
} else if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}

//两个队列实现栈结构
public static class TwoQueuesStack {
private Queue<Integer> data;
private Queue<Integer> help;

public TwoQueuesStack() {
data = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}

public void push(int pushInt) {
data.add(pushInt);
}

public int peek() {
if (data.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while (data.size() != 1) {
help.add(data.poll());
}
int res = data.poll();
help.add(res);
swap();
return res;
}

public int pop() {
if (data.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while (data.size() > 1) {
help.add(data.poll());
}
int res = data.poll();
swap();
return res;
}

private void swap() {
Queue<Integer> tmp = help;
help = data;
data = tmp;
}

}

}



举报

相关推荐

0 条评论