Reading Notes
Ref: http://interactivepython.org/courselib/static/pythonds/BasicDS/stacks.html
STACK: LIFO last-in first-out
Examples in life: books, browser records, etc.
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 ()
Judge whether the stack is empty
Size ()
Returns the number of elements in the stack.
Simple cases and operation results:
Stack Operation Stack Contents Return Values.isEmpty() [] Trues.push(4) [4] s.push('dog') [4,'dog'] s.peek() [4,'dog'] 'dog's.push(True) [4,'dog',True] s.size() [4,'dog',True] 3s.isEmpty() [4,'dog',True] Falses.push(8.4) [4,'dog',True,8.4] s.pop() [4,'dog',True] 8.4s.pop() [4,'dog'] Trues.size() [4,'dog'] 2
Here we use the python list object to simulate stack implementation:
# 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 ())