用python实现栈

闲话不说,上代码

#! /usr/bin/python

class PopOnEmptyStackError(Exception):
	'''A user-defined exception class.'''

	def __init__(self):
		Exception.__init__(self)
		
class Stack:
	def __init__(self):
		self.data = []

	def empty(self):
		if (len(self.data)==0):
			return True
		else:
			return False

	def push(self,item):
		self.data.append(item)

	def pop(self):
		try:
			if (len(self.data)==0):
				raise PopOnEmptyStackError
			else:
				self.data.pop()
		except PopOnEmptyStackError:
			print "you can not pop an empty stack!\n"

	def show(self):
		for i in range(0,len(self.data)):
			print (self.data)[i]

# 以下是简单测试
st = Stack()
#st.push(1)
#st.push(2)
st.pop()
st.show()
 

 

你可能感兴趣的:(python)