I have tried Implementing Stacks Using Linked Lists, and would like some tips and tricks regarding optimizations or ways to simplify/compact processes.
It has 3 functions, Push, Pop, and Peek (For checking the top item in stacks)
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Stack:
def __init__(self):
self.bottom = None
self.top = None
self.length = 0
def peek(self):
return self.top.data if self.top != None else None
def push(self, data):
NewNode = Node(data)
if self.length == 0:
self.bottom = self.top = NewNode
else:
top = self.top
self.top = NewNode
self.top.next = top
self.length += 1
return self
def pop(self):
length = self.length
top = self.top
if length == 0:
raise IndexError('No items in stack')
elif self.bottom == top:
self.bottom = None
else:
NextTop = self.top.next
self.top = NextTop
self.length -= 1
return top.data
Output:
stack = Stack()
stack.push(0)
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
stack.push(5)
stack.push(2)
print(stack.pop())
print(stack.pop())
-----------------------
3
3
2
1
0
2
5
-----------------------