Stack
Stack, which is called a stack, is a container that can be stored in data elements, access elements, delete elements, and it is characterized only by allowing the addition of data (English: Push) and output data (English: Pop) to one end of the container (called the stack Top indicator, English: top). Without a location concept, it is guaranteed that any element that can be accessed or deleted at any time is the one that was last deposited, and a default access order was determined.
Because the stack data structure is only allowed to operate at one end, it operates according to the principle of last-in-first-out.
Enclose the complete code:
class Stack (object): def __init__ (self):
#初始化 Self.items=[] def Empty (self):
#判断是否为空 return Self.items = = [ ]def push (Self,item):
#压栈 self.items.append (item) def pop (self):
#进栈 return self.items.pop () def Peek (self):
#返回栈顶 return Self.items[len (self.items)-1] def size (self):
#返回长度 return Len (self.items) if __name__ " __main__ " :
#站函数 Stack=Stack () Stack.push ("Hello") Stack.push ("python") Stack.push ("Itcast") Print(Stack.size ())Print(Stack.peek ())Print(Stack.pop ())Print(Stack.pop ())Print(Stack.pop ())
Stack of Python data structures