class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def peek(self):
return self.top.value
def push(self, value):
if self.isEmpty():
newNode = Node(value)
self.bottom = newNode
self.top = newNode
else:
newNode = Node(value, self.top)
self.top = newNode
self.length+=1
def pop(self):
if self.isEmpty():
raise Exception("Stack is empty.")
elif self.top == self.bottom:
returnVal = self.bottom.value
self.top = None
self.bottom = None
else:
returnVal = self.top.value
self.top = self.top.next
self.length-=1
return returnVal
def isEmpty(self):
return (True if self.length == 0 else False)
print("Hello World!")
myStack = Stack()
print(myStack.isEmpty())
assert(myStack.isEmpty() == True)
myStack.push(5)
myStack.push(8)
assert(myStack.isEmpty() == False)
assert(myStack.peek()==8)
print(myStack.pop())
assert(myStack.peek()==5)
print(myStack.pop())
assert(myStack.isEmpty() == True)
try:
print(myStack.pop())
except Exception as e:
print(f"exception: {e}")
print("Goodbye Cruel World")