7 class sqstack(object): 8 def __init__(self,maxsize): 9 self.maxsize = maxsize 10 self.stackElem = [] 11 self.top = 0 12 13 def clear(self): 14 self.top = 0 15 def isEmpty(self): 16 return self.top == 0 17 def length(self): 18 return self.top 19 def gettop(self): 20 if not self.isEmpty(): 21 return self.stackElem[self.top - 1] 22 else: 23 return None 24 def push(self,item): 25 if self.top == self.maxsize: 26 raise Exception("栈已满") 27 else: 28 self.stackElem.append(item) 29 self.top += 1 30 def pop(self): 31 if self.isEmpty(): 32 return None 33 else: 34 self.top -= 1 35 values = self.stackElem[self.top] 36 del self.stackElem[self.top] 37 return values 38 def display(self): 39 for i in self.stackElem: 40 print(i,end = " ") 41 print() 42 43 if __name__ == "__main__": 44 sqstack1 = sqstack(5) 45 sqstack1.push(1) 46 sqstack1.push(2) 47 sqstack1.push(3) 48 sqstack1.push(4) 49 sqstack1.push(5) 50 print(sqstack1.gettop()) 51 sqstack1.display() 52 print(sqstack1.length()) 53 print(sqstack1.pop()) 54 sqstack1.display()
运行结果:
5
1 2 3 4 5
5
5
1 2 3