Defined:
Stack, aka stacks, is a linear table in which operations are limited. The limitation is that only one end of the table is allowed to insert and delete operations. This end is called the top of the stack, and the opposite end is called the bottom of the stack. Inserting a new element into a stack, also known as a stack, a stack, or a stack, is to put a new element on top of the stack, making it a new stack top element, deleting an element from a stack, or making a stack or fallback, by removing the top element of the stack and making its adjacent elements a new stack top element.
Features: LIFO
Code:
# Encoding=utf-8
Class Node (object):
def __init__ (Self, VAR):
Self.var = var
Self.next = None
Class Stack (object):
def __init__ (self):
Self.top = None
#进栈的逻辑: Top points to the data that just came in, the previous data becomes the top previous data
def push (Self,var):
If var! = None:
Packnode = Node (Var)
Packnode.next = Self.top
Self.top = Packnode
Return Packnode.var
Else
Return None
#出栈的逻辑: Print top of stack element, top pointing to Next
def pop (self):
if self.top = = None:
Return None
Else
TMP = Self.top.var
Self.top = Self.top.next
return tmp
#获取栈顶元素peek ()
def peek (self):
if self.top = = None:
Return None
Else
Return Self.top.var
#写一个实例方法: Gets the value of the bottom element of the stack, and on the basis of the previous question, prints the value of the bottom element, which is usually not
To, just to deepen the understanding of the stack.
Def bottom (self):
if self.top = = None:
Return None
node = Self.top
While Node.next! = None:
node = Node.next
Return Node.var
#进栈1, 4,5,2,3, then 3 nodes out of the stack, using the Peek method to return the value of the top node of the stack
If __name__== ' __main__ ':
s = Stack ()
NodeList = [1,4,5,2,3]
For I in NodeList:
S.push (i)
For I in range (0,len (nodeList)-2):
S.pop ()
Print S.peek ()
Print S.bottom ()
Python algorithm-Stack