forked from itcharge/AlgoNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack-LinkStack.py
More file actions
46 lines (36 loc) · 923 Bytes
/
Stack-LinkStack.py
File metadata and controls
46 lines (36 loc) · 923 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
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 == None
# 入栈操作
def push(self, value):
cur = Node(value)
cur.next = self.top
self.top = cur
# 出栈操作
def pop(self):
if self.is_empty():
raise Exception('Stack is empty')
else:
cur = self.top
self.top = self.top.next
del cur
# 获取栈顶元素
def peek(self):
if self.is_empty():
raise Exception('Stack is empty')
else:
return self.top.value
stack = Stack()
for i in range(5):
stack.push(i)
for i in range(3):
stack.pop()
print(stack.peek())