Skip to content

Instantly share code, notes, and snippets.

@jaxlo
Last active March 19, 2023 03:25
Show Gist options
  • Save jaxlo/429bafeb3521451af1ff9fe9e6bd09c7 to your computer and use it in GitHub Desktop.
Save jaxlo/429bafeb3521451af1ff9fe9e6bd09c7 to your computer and use it in GitHub Desktop.
A Python stack implementation (Linked list)
# This stack was programmed by Jackson Lohman for part of a CS2420 assignment
class Stack:
def __init__(self):
self.head = None
def push(self, item):
""" Push an item onto the stack. Size increases by 1 """
if self.head is None:
self.head = self.Node(value=item)
else:
after = self.head
self.head = self.Node(value=item)
self.head.next = after
return self.head.value
def pop(self):
""" Remove the top item from the stack and return it. Raise an IndexError if the stack is empty """
if self.head is None:
return None
else:
popped_value = self.head.value
self.head = self.head.next
return popped_value
def top(self):
""" Return the item on top of the stack without removing it. Raise an IndexError if the stack is empty """
if self.head is None:
return None
else:
return self.head.value
def size(self):
""" Return the number of items on the stack """
count = 0
current = self.head
while current is not None:
count += 1
current = current.next
return count
def clear(self):
""" Empty the stack """
self.head = None
class Node:
def __init__(self, value):
self.value = value
self.next = None
# Quick test code
def main_ja():
stack = Stack()
print(stack.size())
print(stack.push('j'))
print(stack.push('a'))
print(stack.top())
print(stack.push('x'))
print(stack.size())
print(stack.pop())
print(stack.pop())
print(stack.size())
# Only j
print(stack.top())
print(stack.push('a'))
print(stack.push('x'))
print(stack.clear())
print(stack.size())
if __name__=="__main__":
main_ja()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment