In this paper, the implementation of stack in Python algorithm is presented as an example, which has some referential value for learning data structure domain algorithm. The specific contents are as follows:
1. Stack stack common operations:
Stack () to create an empty stack object
Push () Adds an element to the topmost layer of the stack
Pop () removes the topmost element of the stack and returns this element
Peek () returns the topmost element and does not delete it
IsEmpty () Determine if the stack is empty
Size () returns the number of elements in the stack
2. Simple case and operation result:
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
This uses the Python list object to simulate the implementation of the stack, with the following code:
#coding: Utf8class stack: "" " Analog Stack" "" def __init__ (self): self.items = [] def isEmpty (self): Return Len (self.items) ==0 def push (self, item): self.items.append (item) def pops (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 ())
Interested readers can try to test the example code described in this article, I believe you will learn python can have a certain harvest.