[Data Structure] Stack Implementation in Python

We can realize a Stack as an adaptation of a Python List.

S.push(e)=L.append(e)

S.pop()=L.pop()

S.top()=L[-1]

S.len()=len(L)

S.is_empty=(len(L)==0)

class Empty(Exception):
	pass

class ArrayStack:
	"""LIFO Stack implementation using Python"""

	def __init__(self):
		self._data=[]

	def __len__(self):
		return len(self._data)

	def is_empty(self):
		return len(self._data)==0

	def push(self,e):
		self._data.append(e)

	def pop(self):
		if self.is_empty():
			raise Empty('Stack is empty')
		return self._data.pop()

	def top(self):
		if self.is_empty():
			raise Empty('Stack is empty')
		return self._data[-1]

  

posted on 2018-09-17 12:32  chiyeung  阅读(98)  评论(0编辑  收藏  举报

导航