02-stack

栈就好像是一个桶,往里加数据(push)和拿数据(pop),先进入桶的在桶底,后进入的在桶顶(top),出数据的时候先出桶顶的。遵循后进先出原则(LIFO, Last In First Out)。

python代码实现:

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
class :
def __init__(self,value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self,value):
node = Node(value)
node.next = self.top
self.top = node
def pop(self):
node = self.top
self.top = node.next
return node.value
if __name__ == '__main__':
stack = Stack()
for i in range(10):
stack.push(i)
while stack.top:
print(stack.pop())

代码解读图示:

stack.push(i)

Alt text

stack.pop()

Alt text