In this paper, the implementation of stack in Python algorithm is illustrated by example, which has some reference value for learning data structure domain algorithm. The specific contents are as follows:
1. Stack stack The usual operation:
Stack () to create an empty stack object
Push () Adds an element to the topmost level of the stack
Pop () deletes the topmost element of the stack and returns the element
Peek () returns the topmost element and does not delete it
IsEmpty () to determine whether 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 Python's list object to simulate the implementation of the stack, as follows:
#coding: UTF8
class 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 test the example code described in this article, I believe that you will learn python can have a certain harvest.