Skip to content

Instantly share code, notes, and snippets.

@srakowski
Created December 22, 2020 22:26
Show Gist options
  • Save srakowski/be9df0c1d23e7eefb7fb2dd77ef853ec to your computer and use it in GitHub Desktop.
Save srakowski/be9df0c1d23e7eefb7fb2dd77ef853ec to your computer and use it in GitHub Desktop.
Linked List in Python based on fruit
# House - Memory
# FruitBowl, Table, Stove, Couch, TVStand - Specific addresses in Memory
# Orange, Apple, Banana - Data we want stored in Memory
# Note - Contains specific address in memory or <None>
# House[FruitBowl] -> Note -> Table
# House[Table] -> Orange, Stove
# House[Stove] -> Apple, Couch
# House[Couch] -> Banana, <None>
# House[Stove].Note = House[Couch].Note
# House[TVStand] = (Orange, House[FruitBowl].Note)
# House[FruitBowl].Note = TVStand
class Node:
def __init__(self, item, next_node):
self.item = item
self.next = next_node
class LinkedList:
def __init__(self):
self.next = None
self.count = 0
def prepend(self, item):
self.next = Node(item, self.next)
self.count += 1
def delete(self):
if self.next is not None:
self.next = self.next.next
self.count -= 1
def contains(self, item):
location = self.next
while location is not None:
if location.item == item:
return True
location = location.next
return False
def remove(self, item):
prev = self
location = self.next
while location is not None:
if location.item == item:
prev.next = location.next
self.count -= 1
return
prev = location
location = location.next
def __str__(self):
value = "["
location = self.next
while location is not None:
value = value + location.item + ","
location = location.next
value = value[:-1]
value = value + "]"
return value
fruit_bowl = LinkedList()
fruit_bowl.prepend("banana")
fruit_bowl.prepend("apple")
fruit_bowl.prepend("orange")
print(fruit_bowl.count)
print(fruit_bowl)
print(fruit_bowl.contains("banana"))
fruit_bowl.remove("banana")
print(fruit_bowl.count)
print(fruit_bowl.contains("banana"))
fruit_bowl.prepend("orange")
print(fruit_bowl.count)
print(fruit_bowl)
fruit_bowl.delete()
print(fruit_bowl)
print(fruit_bowl.count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment