Skip to content

Instantly share code, notes, and snippets.

@montali
Created December 1, 2021 11:43
Show Gist options
  • Save montali/4aff6c471023f15fa472ee146f4f4ee4 to your computer and use it in GitHub Desktop.
Save montali/4aff6c471023f15fa472ee146f4f4ee4 to your computer and use it in GitHub Desktop.
Ultra-basic stack and queue implementation for i posteri
class LinkedListNode:
def __init__(self, value=None):
self.value = value
self.next = None
def __repr__(self) -> str:
return str(self.value)
class Stack:
def __init__(self):
self.top = LinkedListNode()
def add(self, data):
node = LinkedListNode(data)
node.next = self.top
self.top = node
def pop(self):
node = self.top
self.top = self.top.next
return node
def peek(self):
print("Peeking!")
pointer = self.top
while pointer.next:
print(pointer.value)
pointer = pointer.next
print("Finished peeking")
class Queue:
def __init__(self):
self.next_in_queue = None
def add(self, data):
if not self.next_in_queue:
self.next_in_queue = LinkedListNode(data)
else:
pointer = self.next_in_queue
while pointer.next:
pointer = pointer.next
pointer.next = LinkedListNode(data)
def pop(self):
node = self.next_in_queue
self.next_in_queue = self.next_in_queue.next
return node
def peek(self):
print("Peeking!")
pointer = self.next_in_queue
while pointer.next:
print(pointer.value)
pointer = pointer.next
print("Finished peeking")
top = LinkedListNode(5)
s = Stack()
s.add(5)
s.add(6)
s.add(7)
print(s.pop())
print(s.pop())
print(s.pop())
print("Now, the queue")
q = Queue()
q.add(5)
q.add(6)
q.add(7)
print(q.pop())
print(q.pop())
print(q.pop())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment