Skip to content

Commit 9616c37

Browse files
committed
stack & queue done for now
1 parent d97eac8 commit 9616c37

File tree

1 file changed

+18
-25
lines changed

1 file changed

+18
-25
lines changed

data_structure/stack_queue.md

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -331,43 +331,34 @@ class Solution:
331331

332332
> 使用栈实现队列
333333
334+
两个栈:输入栈和输出栈。
335+
334336
```Python
335337
class MyQueue:
336338

337339
def __init__(self):
338-
self.cache = []
339-
self.out = []
340+
self.instack = []
341+
self.outstack = []
340342

341343
def push(self, x: int) -> None:
342-
"""
343-
Push element x to the back of queue.
344-
"""
345-
self.cache.append(x)
344+
self.instack.append(x)
346345

347346
def pop(self) -> int:
348-
"""
349-
Removes the element from in front of queue and returns that element.
350-
"""
351-
if len(self.out) == 0:
352-
while len(self.cache) > 0:
353-
self.out.append(self.cache.pop())
354-
355-
return self.out.pop()
347+
if not self.outstack:
348+
while self.instack:
349+
self.outstack.append(self.instack.pop())
350+
351+
return self.outstack.pop()
356352

357353
def peek(self) -> int:
358-
"""
359-
Get the front element.
360-
"""
361-
if len(self.out) > 0:
362-
return self.out[-1]
363-
else:
364-
return self.cache[0]
354+
if not self.outstack:
355+
while self.instack:
356+
self.outstack.append(self.instack.pop())
357+
358+
return self.outstack[-1]
365359

366360
def empty(self) -> bool:
367-
"""
368-
Returns whether the queue is empty.
369-
"""
370-
return len(self.cache) == 0 and len(self.out) == 0
361+
return not (self.instack or self.outstack)
371362
```
372363

373364
### [binary-tree-level-order-traversal](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)
@@ -519,6 +510,8 @@ class Solution:
519510

520511
> 求滑动窗口中的最大元素
521512
513+
先掌握堆的做法即可。
514+
522515
```Python
523516
class Solution:
524517
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:

0 commit comments

Comments
 (0)