Skip to content

Instantly share code, notes, and snippets.

Created Feb 11, 2019
What would you like to do?
Single Linked List class implementation from the book 'Learn More Python The Hard Way'
# manually build a list using the SingleLinkedListNode class
# Zed' code
class SingleLinkedListNode(object):
def __init__(self, value, nxt):
self.value = value = nxt
def __repr__(self):
nval = and or None
return f"[{self.value}:{repr(nval)}]"
# controller class for the SLLN
class SingleLinkedList(object):
def __init__(self):
self.begin = None
self.end = None
self.num_nodes = 0
# add a new node
def push(self, obj):
"""Appends a new value on the end of the list."""
if self.begin is None:
self.begin = SingleLinkedListNode(obj, None)
elif self.end is None:
self.end = SingleLinkedListNode(obj, None) = self.end
new_node = SingleLinkedListNode(obj,None) = new_node
self.end = new_node
self.num_nodes += 1
def pop(self):
"""Removes the last item and returns it."""
if self.begin is None: # empty list
return None
elif self.end is None and self.begin is not None: # only self.begin
rv = self.begin.value
self.begin = None
self.num_nodes -=1
return rv
else: # list contains 2 or more than elements
iterator = 0
previous_node = self.begin # start list traversal here
next_node =
while iterator < self.num_nodes: # or just while True?
if next_node is self.end:
rv = next_node.value
self.end = previous_node = None
self.num_nodes -= 1
return rv
if next_node is None:
print(">>> this never happens does it?")
rv = next_node.value = None
if self.num_nodes == 1:
print(">>> pretty sure this will never run.")
self.end = None
self.end = previous_node
self.num_nodes -= 1
return rv
previous_node = next_node
next_node =
iterator += 1
def shift(self, obj):
"""Another name for push."""
def unshift(self):
"""Removes the first item and returns it."""
def remove(self, obj):
"""Finds a matching item and removes it from the list."""
def first(self):
"""Returns a *reference* to the first item, does not remove."""
def last(self):
"""Returns a reference to the last item, does not remove."""
def count(self):
"""Return the number of elements in the list"""
return self.num_nodes
def get(self, index):
"""Get the value at index."""
def dump(self, mark):
"""Debugging function that dumps the contents of the list."""
from sllist import *
# import pdb; pdb.set_trace()
def test_push():
colors = SingleLinkedList()
colors.push("Pthalo Blue")
assert colors.count() == 1
colors.push("Ultramarine Blue")
assert colors.count() == 2
def test_pop():
colors = SingleLinkedList()
colors.push("Tomato Red")
assert colors.pop() == "Tomato Red"
assert colors.pop() == "Alizarin"
assert colors.pop() == "Magenta"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment