思路:
1、一个栈存放进入的元素
2、另外一个栈,删除元素,如果没有元素,则把上一个栈的元素入栈后删除元素
代码:
package com.datastructure.stackqueue;
import java.util.Stack;
/**
* 两个栈实现一个队列
*
* 添加元素时 向stack1中添加
*
* 删除元素时 从stack2中删除
*
*/
public class QueueByStack<T> {
// 存放插入的元素
private Stack<T> stack1 = new Stack<T>();
// 删除元素时使用
private Stack<T> stack2 = new Stack<T>();
/**
* =================================================================
* 版本一:保证两个栈中,同时只有一个栈有元素,职责清晰,但是插入元素性能稍低
* =================================================================
*/
/**
* 新增元素到尾部
*
*
*
*/
public void appendTail(T t) {
if (stack1.empty() && stack2.empty()) {
stack1.push(t);
return;
}
if (stack1.empty() && !stack2.empty()) {
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
stack1.push(t);
return;
}
if (!stack1.empty() && stack2.empty()) {
stack1.push(t);
}
}
/**
* 删除头部元素
*/
public T deleteHead() {
if (stack1.empty() && stack2.empty()) {
throw new RuntimeException("queue is empty");
}
if (stack1.empty() && !stack2.empty()) {
return stack2.pop();
}
if (!stack1.empty() && stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
return null;
}
/**
* =================================================================
* 版本二:插入时,只管插入即可,弹出元素时先从stack2中取,没有在把stack1中元素
* 压入stack2栈中
* =================================================================
*/
public void appendTail1(T t) {
stack1.push(t);
}
/**
* 删除头部元素
*/
public T deleteHead1() {
if (stack1.empty() && stack2.empty()) {
throw new RuntimeException("queue is empty");
}
if (!stack1.empty() && stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
// stack2非空
return stack2.pop();
}
@Override
public String toString() {
return this.stack1.toString() + ", " + this.stack2.toString();
}
public static void main(String[] args) {
QueueByStack<Integer> q = new QueueByStack<>();
q.appendTail(1);
q.appendTail(2);
q.appendTail(3);
q.deleteHead();
q.appendTail(4);
System.out.println(q);
QueueByStack<Integer> q1 = new QueueByStack<>();
q1.appendTail1(1);
q1.appendTail1(2);
q1.appendTail1(3);
q1.deleteHead1();
q1.appendTail1(4);
System.out.println(q1);
}
}