Idea and implementation of data structure must be able stack (Python)


1. What is the stack

​ 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 .

 Insert picture description here

​ 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 :

 Insert picture description here

2. The realization of the stack

​ 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):
# Out of the stack 
def pop(self):
# 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()
# Output 
# Test code 
# Output 
Please bring the original link to reprint ,thank
Similar articles