
题目:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
思路:
首先定义两个栈stack1、stack2,stack1用于插入,stack2用于删除。删除时如果直接出栈就无法实现先进先出,这时需要将stack1中的所有元素从stack1出栈,然后依次压入stack2中,然后再从stack2中出栈。如果stack2中有元素存在,那么直接出栈,无需将stack1中元素压入stack2中。只有当stack2中元素都为空时,才需要将stack1中元素取出。
代码:
import java.util.Stack; /** * 两个栈实现队列 * @author wydream * */ public class TwoStackQueue { private Stack<Object> s1;//s1插入元素 private Stack<Object> s2;//s2删除元素 public TwoStackQueue() { s1=new Stack<Object>(); s2=new Stack<Object>(); } //插入元素 public void push(Object obj) { s1.push(obj); } //元素出队列 public Object pop() { if(s2.empty()&&s1.empty()) { return null; } if(s2.empty()) { System.out.println("s1中数据进入到s2"); while(!s1.empty()) { Object obj=s1.pop(); s2.push(obj); } } return s2.pop(); } public static void main(String[] args) { TwoStackQueue tq=new TwoStackQueue(); tq.push("北京"); tq.push("上海"); tq.push("深圳"); tq.push("杭州"); System.out.println(tq.pop()); System.out.println(tq.pop()); System.out.println(tq.pop()); tq.push("武汉"); System.out.println(tq.pop()); System.out.println(tq.pop()); } }
相关题目——两个队列实现栈:
import java.util.LinkedList; import java.util.Queue; /** * 两个队列实现栈 * * @author wydream * */ public class TwoQueueStack { private Queue<String> queue1=new LinkedList<String>(); private Queue<String> queue2=new LinkedList<String>(); //向栈中压入元素 public void push(String value) { //两个队列都为空时,优先考虑queue1 if(queue1.isEmpty()&&queue2.isEmpty()) { queue1.add(value); return; } //如果queue1为空,queue2中有数据,则直接放入queue2中 if(queue1.isEmpty()) { queue2.add(value); return; } //如果queue2为空,queue1有数据,直接放入queue1中 if(queue2.isEmpty()) { queue1.add(value); return; } } //从栈中弹出一个数据 public String pop() { //两个栈都为空 if(queue1.isEmpty()&&queue2.isEmpty()) { System.out.println("栈为空"); return null; } //如果queue1中没有元素,queue2中有元素,将其queue2中的元素依次放入queue1中,直到最后一个元素,弹出即可 if(queue1.isEmpty()) { while(queue2.size()>1) { queue1.add(queue2.poll()); } return queue2.poll(); } //如果queue2中没有元素,queue1中有元素,将其queue1中的元素依次放入queue2中,直到最后一个元素,弹出即可 if(queue2.isEmpty()) { while(queue1.size()>1) { queue2.add(queue1.poll()); } return queue1.poll(); } return null; } public static void main(String[] args) { TwoQueueStack ts=new TwoQueueStack(); ts.push("北京"); ts.push("上海"); ts.push("广州"); ts.push("深圳"); System.out.println(ts.pop()); System.out.println(ts.pop()); ts.push("苏州"); ts.push("杭州"); System.out.println(ts.pop()); System.out.println(ts.pop()); } }