-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackQueueHeap.py
More file actions
70 lines (51 loc) · 1.22 KB
/
StackQueueHeap.py
File metadata and controls
70 lines (51 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import heapq
def build_heap(vals):
heap = []
for val in vals:
heapq.heappush(heap, val)
return heap
def pop_heap(heap):
return heapq.heappop(heap)
def adjust(heap):
heapq.heapify(heap)
return heap
def main():
heap = build_heap([0, 1, 2, 3, 4, 5])
print(heap)
print(pop_heap(heap))
print(heap)
heap = [1, 5, 3, 7, 4, 7]
print(adjust(heap))
return
# stack but linklist
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def insert(self, v):
node = Node(v)
node.next = self.top
self.top = node
def pop(self):
if self.is_empty():
return None
else:
cur = self.top
self.top = self.top.next
return cur
# monotone Stack
def monotoneIncreasingStack(nums):
stack = []
for num in nums:
while stack and num >= stack[-1]:
stack.pop()
stack.append(num)
# stack: list pop from tail, list append from tail
# queue: list append from tail, pop with list.pop(0)
if __name__ == '__main__':
main()