# What is a stack, in simple terms: last in, first out.

## Algorithm principle

• Push to the stack (PUSH) algorithm
1. If TOP≥n, an overflow message will be given and an error handling will be made (before entering the stack, first check whether the stack is full, overflow if it is full; do 2 if it is not full)
2. Set TOP=TOP+1 (add 1 to the stack pointer to point to the stack address)
3. S(TOP)=X, end (X is the new element on the stack)
• Unstack (POP) algorithm
1. If TOP≤0, an underflow information will be given, and an error handling will be made (check whether the stack is empty before exiting the stack, if it is empty, it will underflow; if it is not empty, then it will be 2)
2. X=S(TOP), (the elements after unstacking are assigned to X)
3. TOP=TOP-1, end (stack pointer minus 1, pointing to the top of the stack)

## Algorithm implementation

``````# - * - coding : utf -8  - * -

__author__ =  'Bitter leaves'

class  Stack :
def __init__ ( self , size = 30 ) :
# Initialize stack size
self . size = size

# Initialize the stack list
self . stack =  [ ]

# Initialize the stack default top value
Self . Top =  - . 1

# Set stack size
def set_size ( self , size ) :
self . size = size

# Determine whether the stack is empty
def is_empty ( self ) :
res = False
if self . top ==  - 1 :
res = True

return res

# Determine if the stack is full
def is_full ( self ) :
res = False
if self . top +  1  == self . size :
res = True

return res

# Print everything in the stack
def show ( self ) :
print ( self . stack )     # into the stack
def push ( self , obj ) :
if self . is_full ( ) :
raise Exception ( "The stack is full..." )
else :
self . stack . append ( obj )
self . top +=  1

# Unstack
def pop ( self ) :
if self . is_empty ( ) :
raise Exception ( "The stack is empty..." )
else :
self . top -=  1
return self . stack . pop ( )

if __name__ ==  "__main__" :

print ( "stack implementation example" )
# Initially a stack instance with a length of 5
stack =  Stack ( 5 )

# Stack integer 1 - 5
for index in  the Range ( 1 ,  6 ) :
Stack . The Push ( index )

# Print the contents of the next stack
Stack . Show ( )

# The stack , the value of the data should be . 5
data = Stack . POP ( )
Print ( data )

# Print the contents of the stack, which should be [ 1 , 2 , 3 , 4 ]
stack . Show ( )``````