xxxxxxxxxx
#an exception to be raised by an empty stack
class Empty(Exception):
pass
class Stack:
class _Node:
def __init__(self, e, n):
self._element = e #Users element
self._next = n #The next node in the list
def __init__(self):
self._head = None #Reference the first node in the linked list
self._size = 0 #The number of elements in the stack
def __len__(self):
return self._size
def is_empty(self):
return len(self) == 0
def push(self, e):
#add a new element to the stack
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
if self.is_empty():
raise Empty("Stack is empty.")
return self._head._element
def pop(self):
if self.is_empty():
raise Empty("Stack is empty.")
element = self._head._element
self._head = self._head._next # make the
self._size -= 1
return element
# test the stack
S = Stack()
S.push(10)
S.push(20)
S.push(30)
S.push(40)
S.push(50)
print("Size: ", len(S))
while not S.is_empty():
print(S.pop())
xxxxxxxxxx
#an exception to be raised by an empty stack
class Empty(Exception):
pass
class Stack:
class _Node:
def __init__(self, e, n):
self._element = e #Users element
self._next = n #The next node in the list
def __init__(self):
self._head = None #Reference the first node in the linked list
self._size = 0 #The number of elements in the stack
def __len__(self):
return self._size
def is_empty(self):
return len(self) == 0
def push(self, e):
#add a new element to the stack
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
if self.is_empty():
raise Empty("Stack is empty.")
return self._head._element
def pop(self):
if self.is_empty():
raise Empty("Stack is empty.")
element = self._head._element
self._head = self._head._next # make the
self._size -= 1
return element
# test the stack
S = Stack()
S.push(10)
S.push(20)
S.push(30)
S.push(40)
S.push(50)
print("Size: ", len(S))
while not S.is_empty():
print(S.pop())