First, take an example in life ： When the dishes are stacked together, it is a stack structure , When using the plate, only the top one can be taken away , When placing, the one washed first will be placed at the bottom , This constitutes an idea of putting first and taking later , That's our idea .
A stack is an ordered collection , Its add and remove operations always occur in “ Apex ”（ The other end is called the bottom end ）, The closer the elements in the stack are to the bottom , Represents the longer it is in the stack , The sorting principle of the stack is called LIFO（last-in first-out）, The specific implementation method is shown in the figure below ：
In the use of Python When implementing the stack , Can use Python Middle list （list） To achieve , In the list append() Functions can be implemented to add elements at the end （ Backward operation ）,pop() Function can push out the last element （ First out operation ）, The specific implementation method is as follows ：
# establish class Stack class Stack: # Initialization stack def __init__(self): self.items =  # Judge whether the stack is empty def isEmpty(self): return self.items ==  # Push def push(self, item): self.items.append(item) # Out of the stack def pop(self): self.items.pop() # Return the element at the top of the stack def peek(self): return self.items[len(self.items) - 1] # Returns the number of elements in the stack def size(self): return len(self.items)
The test results are as follows ：
# Test code s = Stack() s.isEmpty() # Output True # Test code s.push('I') s.push('like') s.push('python') s.pop() s.peek() s.size() # Output 2
本文为[The second brother is not like a programmer]所创，转载请带上原文链接，感谢