This article mainly introduces the implementation of the Python algorithm stack, which is very practical. if you need it, you can refer to the following example to demonstrate the implementation of the stack in the Python algorithm, it has some reference value for learning data structure domain algorithms. The details are as follows:
1. stack operations:
Stack () creates an empty Stack object
Push () adds an element to the top layer of the stack
Pop () deletes the top-level element of the stack and returns this element.
Peek () returns the top-level element and does not delete it.
IsEmpty () determines whether the stack is empty
Size () returns the number of elements in the stack.
2. simple cases and operation results:
Stack Operation Stack Contents Return Value s.isEmpty() [] True s.push(4) [4] s.push('dog') [4,'dog'] s.peek() [4,'dog'] 'dog' s.push(True) [4,'dog',True] s.size() [4,'dog',True] 3 s.isEmpty() [4,'dog',True] False s.push(8.4) [4,'dog',True,8.4] s.pop() [4,'dog',True] 8.4 s.pop() [4,'dog'] True s.size() [4,'dog'] 2
Here we use the python list object to simulate stack implementation. the specific code is as follows:
# Coding: utf8class Stack: "simulate Stack" def _ init _ (self): self. items = [] def isEmpty (self): return len (self. items) = 0 def push (self, item): self. items. append (item) def pop (self): return self. items. pop () def peek (self): if not self. isEmpty (): return self. items [len (self. items)-1] def size (self): return len (self. items) s = Stack () print (s. isEmpty () s. push (4) s. push ('dog ') print (s. peek () s. push (True) print (s. size () print (s. isEmpty () s. push (8.4) print (s. pop () print (s. pop () print (s. size ())
If you are interested, you can test the sample code described in this article. I believe it will be helpful for everyone to learn Python.