Python stack operation example for implementing the basic data structure, python Data Structure
This example describes how to implement the stack operation in the basic data structure of Python. We will share this with you for your reference. The details are as follows:
#! /Usr/bin/env python # coding = UTF-8 # Python implements the basic data structure --- Stack operation class Stack (object): def _ init _ (self, size): self. size = size self. stack = [] self. top = 0 # initialization. if top = 0, the empty stack def push (self, x): if self. stackFull (): # Check whether the stack is full raise Exception ("overflow! ") Else: self. stack. append (x) self. top = self. top + 1 # The first element subscript pushed in is 1 def pop (self): if self. stackEmpty (): raise Exception ("underflow! ") Else: self. top = self. top-1 return self. stack. pop () # Use the Python built-in function pop () to bring up def stackEmpty (self): if self. top = 0: # judge stack NULL return True else: return False def stackFull (self): if self. top = self. size: # judge that the stack is full !!! Return True else: return Falseif _ name _ = '_ main _': print "helper's house Test Result:" s = Stack (10) for I in range (3): s. push (I) print s. stack print s. pop () print s. stack print s. pop () print s. pop () print s. stack print s. stackEmpty () print s. stackFull () for I in range (10): s. push (I) print s. stackFull ()
Running result: