-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathlinked_stack.py
More file actions
53 lines (38 loc) · 1001 Bytes
/
linked_stack.py
File metadata and controls
53 lines (38 loc) · 1001 Bytes
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
# 使用链表实现的栈
class ListNode:
def __init__(self, val: int):
self.val = val
self.next = None
class LinkedStack:
def __init__(self, capacity: int):
self.head = None
self.size = 0
self.capacity = capacity
# 入栈
def push(self, val: int):
if self.size >= self.capacity:
raise RuntimeError('the stack is full')
node = ListNode(val)
if self.head:
node.next = self.head
self.head = node
self.size += 1
# 出栈
def pop(self):
if self.size <= 0:
raise RuntimeError('the stack is empty')
res = self.head.val
self.head = self.head.next
self.size -= 1
return res
if __name__ == '__main__':
stack = LinkedStack(10)
stack.push(1)
stack.push(5)
stack.push(8)
print(stack.pop())
print(stack.pop())
print(stack.pop())
stack.push(10)
stack.push(21)
print(stack.pop())