Skip to content

Commit c5efa8e

Browse files
authored
Finished Interview-9
1 parent ea76240 commit c5efa8e

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

Algorithm/Interview-9.md

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
## Inverview-9:用两个栈实现队列
2+
3+
**题目**:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。
4+
5+
1. 创建一个栈类。
6+
2. 创建一个队列类,该队列类包含两个栈stack1和stack2,当需要添加元素到队列时,其实就是往stack1中入栈。
7+
3. 如果是要消费队列时,需要先判断stack2是否为空,如果为空,那么就把stack1中的数据逐个出栈并对stack2入栈,这样就使得先进来的数据在stack2的栈顶,实现了队列的先进先出原则;如果不为空,那么stack2直接出栈。
8+
9+
```python
10+
## 栈的实现 后进先出
11+
class Stack():
12+
def __init__(self):
13+
self.stack = []
14+
self.top = -1
15+
16+
def push(self, x): # 入栈之前检查是否满了
17+
self.stack.append(x)
18+
self.top += 1
19+
20+
def pop(self): # 出栈之前检查是否为空
21+
if self.isempty():
22+
return None
23+
else:
24+
self.top = self.top - 1
25+
pop_value = self.stack[self.top + 1]
26+
del self.stack[self.top + 1]
27+
return pop_value
28+
29+
def isempty(self):
30+
return self.top == -1
31+
32+
def showstack(self):
33+
print(self.stack)
34+
35+
def get_deep(self):
36+
return self.top + 1
37+
38+
## 两个栈实现一个队列
39+
class Queue():
40+
def __init__(self):
41+
self.stack_one = Stack()
42+
self.stack_two = Stack()
43+
self.deep = 0
44+
45+
## 向队列添加数据
46+
def append(self, x):
47+
self.stack_one.push(x)
48+
self.deep += 1
49+
50+
## 取出队列的数据
51+
def get_head(self):
52+
if self.isempty():
53+
return None
54+
elif self.stack_two.isempty():
55+
while not self.stack_one.isempty():
56+
self.stack_two.push(self.stack_one.pop())
57+
58+
self.deep = self.deep - 1
59+
return self.stack_two.pop()
60+
61+
62+
def isempty(self):
63+
return self.deep == 0
64+
65+
queue = Queue()
66+
queue.append('a')
67+
queue.append('b')
68+
queue.append('c')
69+
print(queue.get_head())
70+
print(queue.get_head())
71+
72+
queue.append('d')
73+
print(queue.get_head())
74+
print(queue.get_head())
75+
```
76+
77+
a
78+
79+
b
80+
81+
c
82+
83+
d
84+
85+
**Inverview-9测试用例**
86+
87+
```python
88+
## 往空队列里添加元素和删除元素
89+
queue = Queue()
90+
queue.append('a')
91+
print(queue.get_head())
92+
print(queue.get_head())
93+
```
94+
95+
a
96+
97+
None
98+
99+
> 作者:[@mantchs](https://github.com/NLP-LOVE/ML-NLP)
100+
>
101+
> GitHub:[https://github.com/NLP-LOVE/CodingInterviews2-ByPython](https://github.com/NLP-LOVE/CodingInterviews2-ByPython)
102+
>
103+
> 有意向一起完成此项目或者有问题、有补充的可以加入《剑指offer》讨论群【818185620】<a target="_blank" href="//shang.qq.com/wpa/qunwpa?idkey=8c188e86e0eac4a214861c2c706a9c0baf75176e16e52f07b8a64d1a13f99a0d"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="《剑指offer》讨论群" title="《剑指offer》讨论群"></a>

0 commit comments

Comments
 (0)