Skip to content

Commit 85b60df

Browse files
committed
add 面试题9 用两个栈实现一个队列
1 parent f8f8b52 commit 85b60df

6 files changed

Lines changed: 88 additions & 13 deletions

File tree

Algorithm/剑指offer/coding-interviews/.idea/workspace.xml

Lines changed: 19 additions & 13 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.leosanqing.algorithm;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* @Author: leosanqing
7+
* @Date: 2019-11-16 12:47
8+
*
9+
* 面试题9,使用两个栈实现队列
10+
*
11+
*
12+
* 我们先将一个元素入队列,在内部,其实是我们选取一个栈,叫他stack1
13+
*
14+
* 我们将元素a,b,c,d 依次入stack1,这个时候,我们要出栈了。
15+
* 栈是FILO,先入后出。我们将它再依次出栈并入到 stack2。然后stack2再出栈,顺序就对了
16+
* 这个时候,d 出栈了。然后再入 e, e入哪里呢?
17+
*
18+
* 我们把它入到 stack1中,(没入前stack1是空的)。因为如果入到 stack2就出问题了
19+
* 我们把它放到stack1中并不影响 我们出队列的顺序。
20+
*
21+
* 如果再来 f 呢? 我们还是把它入到 stack1.所以不管怎么样,我们总是只入stack1
22+
*
23+
* 出栈的时候就讲究了。如果 stack2有值,那就出栈,没值。要把stack1中所有的元素入到stack2
24+
*
25+
*/
26+
public class _9_ImplementQueueWithStack {
27+
28+
29+
public static void main(String[] args) throws Exception {
30+
MyQueue<String> queue = new MyQueue<String>();
31+
32+
queue.enqueue("a");
33+
queue.enqueue("b");
34+
queue.enqueue("c");
35+
queue.enqueue("d");
36+
System.out.println(queue.dequeue());
37+
queue.enqueue("e");
38+
System.out.println(queue.dequeue());
39+
System.out.println(queue.dequeue());
40+
System.out.println(queue.dequeue());
41+
System.out.println(queue.dequeue());
42+
System.out.println(queue.dequeue());
43+
44+
}
45+
46+
47+
}
48+
49+
class MyQueue<T>{
50+
private Stack<T> stack1 = new Stack<T>();
51+
private Stack<T> stack2 = new Stack<T>();
52+
53+
public void enqueue(T e){
54+
stack1.push(e);
55+
}
56+
57+
public T dequeue() throws Exception {
58+
if(stack1.empty()&&stack2.empty()) {
59+
throw new Exception("队列为空");
60+
}else {
61+
if(stack2.empty()){
62+
while (!stack1.empty()){
63+
stack2.push(stack1.pop());
64+
}
65+
}
66+
return stack2.pop();
67+
}
68+
}
69+
}
Binary file not shown.

0 commit comments

Comments
 (0)