1.两个栈实现队列
package example;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
/**
* 用两个栈实现队列
* 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,
* 分别完成在队列尾部插入节点和在队列头部删除节点的功能。
*
* @author lvtong
* @date 2020/1/30
*/
public class Example9 {
private static Stack<String> stack1 = new Stack<>();
private static Stack<String> stack2 = new Stack<>();
public static void main(String[] args) {
//测试数据
stack1.push("A");
stack1.push("B");
stack1.push("C");
stack1.push("D");
stack2.push("E");
appendTail("H");
deleteHead();
//打印操作结果
System.out.print(stack1.toString());
Collections.reverse(stack2);
System.out.print(stack2);
}
/**
* 删除头节点
*/
private static void deleteHead() {
while (!stack1.isEmpty()) {
String temp = stack1.peek();
stack1.pop();
stack2.push(temp);
}
stack2.pop();
}
/**
* 插入节点
*/
private static void appendTail(String string) {
while (!stack2.isEmpty()) {
String temp = stack2.peek();
stack2.pop();
stack1.push(temp);
}
stack1.push(string);
}
}
2.两个队列实现栈
package example;
import java.util.*;
/**
* 用两个队列实现一个栈
*
* @author lvtong
* @date 2020/1/31
*/
public class Related9 {
/**
* 队列1用来push
*/
private static LinkedList<String> queue1 = new LinkedList<>();
/**
* 队列2用来pop
*/
private static LinkedList<String> queue2 = new LinkedList<>();
public static void main(String[] args) {
//测试数据
queue1.add("a");
queue1.add("b");
queue1.add("c");
//测试方法
pushMethod("D");
popMethod();
pushMethod("E");
popMethod();
popMethod();
}
/**
* 插入方法
*
* @param string 插入数据
*/
private static void pushMethod(String string) {
//插入的数据直接放到队列1
queue1.add(string);
System.out.println("添加了:" + string);
System.out.print("添加结果:" + queue1);
System.out.print(queue2);
System.out.println();
}
/**
* 弹出方法
*/
private static void popMethod() {
//如果队列1中不止一个数据,就出队添加到队列2中
while (queue1.size() != 1) {
String temp = queue1.element();
queue1.remove();
queue2.add(temp);
}
//将队列1中的一个数据弹出
System.out.println("删除了:" + queue1.remove());
//将队列2中的数据重新放回队列1
while (!queue2.isEmpty()) {
queue1.add(queue2.remove());
}
System.out.print("删除结果:" + queue1);
System.out.print(queue2);
System.out.println();
}
}