Reading Notes
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 () determines whether the stack is empty
Size () returns the number of elements in the stack.
Simple cases and operation results:
[Python]
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
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:
[Python]
# Coding: utf8
Class 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 (1, 8.4)
Print (s. pop ())
Print (s. pop ())
Print (s. size ())
# Coding: utf8
Class 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 (1, 8.4)
Print (s. pop ())
Print (s. pop ())
Print (s. size ())