-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathordered_stack.py
More file actions
48 lines (40 loc) · 1.13 KB
/
Copy pathordered_stack.py
File metadata and controls
48 lines (40 loc) · 1.13 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
class OrderedStack:
def __init__(self):
self.top = -1
self.stack = []
def __iter__(self):
t_top = self.top
while True:
if t_top == -1:
break
yield self.stack[t_top]
t_top -= 1
def __len__(self):
return self.top + 1
def size(self):
return len(self)
def is_empty(self):
return self.top == -1
def push(self, val):
if self.is_empty():
self.t_push(val)
else:
tmp_stack = OrderedStack()
while not self.is_empty() and val < self.peek():
tmp_stack.t_push(self.pop())
tmp_stack.t_push(val)
while not tmp_stack.is_empty():
self.t_push(tmp_stack.pop())
def t_push(self, val):
self.stack.append(val)
self.top += 1
def pop(self):
if self.is_empty():
raise IndexError("stack empty")
val = self.stack.pop()
self.top -= 1
return val
def peek(self):
if self.is_empty():
raise IndexError("stack empty")
return self.stack[self.top]