题目描述:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
思路:一个栈压入元素,而另一个栈作为缓冲,将栈1的元素出栈后压入栈2中再出栈。
分析:
1. 在队列尾部插入节点:直接在stack1中压入元素
2. 在队列头部删除节点:
1> 当stack2不为空时,在stack2栈顶的元素是先进入队列的元素,可以弹出。
2> 当stack2为空时,将stack1中的元素逐个弹出并压入stack2中,再从stack2栈顶弹出元素。
package Problem7;
3 import java.util.Stack;
5 public class ConStructQueue {
11 /**
12 * @param args
13 */
14 Stack<String> stack1 = new Stack<String>();
15 Stack<String> stack2 = new Stack<String>();
17 // 实现appendTail函数
18 public void appendTail(String s) {
19 stack1.push(s);
20 }
22 // 实现deleteHead函数
23 public String deleteHead() throws Exception {
24 if (stack2.isEmpty()) {
25 while (!stack1.isEmpty()) {
26 stack2.push(stack1.pop());
27 }
28 }
29 if (stack2.isEmpty()) {
30 throw new Exception("队列为空,不能进行删除操作");
31 }
32 return stack2.pop();
33 }
35 public static void main(String[] args) throws Exception {
36 ConStructQueue test = new ConStructQueue();
37 // 向空的队列中添加元素、删除元素
38 test.appendTail("1");
39 System.out.println(test.deleteHead());
40 // 向非空的队列添加删除元素
41 test.appendTail("2");
42 test.appendTail("3");
43 System.out.println(test.deleteHead());
45 }
47 }
或者
public void push(int node) {
stack1.push(node);
}
public int pop() throws Exception {
if (stack1.isEmpty() && stack2.isEmpty()) {
throw new Exception("栈为空!");
}
if (stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
拓展:用两个队列实现一个栈
思路:1. 压入时:哪个队列不是空的就往哪个队列中添加元素
2. 弹出时:将不为空的队列中的元素依次删除并添加进另一个队列,直至只剩一个元素,并弹出该元素
注意:两个队列中总有一个队列是空的
public class queueToStack {
Queue<Integer> queue1 = new LinkedList<Integer>();
Queue<Integer> queue2 = new LinkedList<Integer>();
public int pop() throws Exception{
if(queue1.isEmpty() && queue2.isEmpty()){
throw new Exception("stack is empty");
}
if(queue1.isEmpty()){
while(queue2.size() > 1){
queue1.add(queue2.poll());
}
return queue2.poll();
}
if(queue2.isEmpty()){
while(queue1.size() > 1){
queue2.add(queue1.poll());
}
return queue1.poll();
}
return (Integer) null;
}
public void push(int num){
if(queue1.isEmpty() && queue2.isEmpty()){
queue1.add(num);
return;
}
if(!queue1.isEmpty()){
queue1.add(num);
return;
}
if(!queue2.isEmpty()){
queue2.add(num);
return;
}
}
}