Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"""Linked List implementation in Python."""
class LinkedCell:
"""Node implementation for linked list."""
def __init__(self, v, n=-1):
"""Construct for LinkedCell."""
self.value = v
self.next = n
self.length = 1
def prepend(self, v):
"""Prepend given value to the linked list."""
newc = LinkedCell(v)
newc.next = self
newc.length = self.length + 1
return newc
def len(self):
"""Calculate length of the linked list."""
length = 0
n = self
while n != -1:
length = length + 1
n = n.next
return length
def seek(self, i):
"""Return the value at index."""
n = self
if i < 0 or i >= self.length:
return -1
while i > 0:
i = i - 1
n = n.next
return n.value
def traverse(self):
"""Traverse the linked list and print node contents."""
n = self
while n != -1:
(print('value: {}, next: {}, length: {}'
.format(n.value, n.next, n.length)))
n = n.next
def simple_traverse(self):
"""Traverse and print only node values."""
n = self
while n != -1:
print('{} -> '.format(n.value), end='')
n = n.next
print('End')
# TODO: assign(nv, i), append(v), insert(v, i), remove(i)
class TestLinkedCell(object):
"""Test suite for LinkedCell."""
def test_creation1(self):
"""Test __init__ functionality."""
l1 = LinkedCell(5)
assert l1.value == 5
assert l1.next == -1
l2 = LinkedCell(6, l1)
assert l2.value == 6
assert l2.next == l1
assert l2.next.value == 5
assert l2.next.next == -1
def test_prepend(self):
"""Test prepend() functionality."""
ll = LinkedCell(5)
ll = ll.prepend(6)
ll = ll.prepend(12)
ll = ll.prepend(76)
ll = ll.prepend(1)
assert ll.value == 1
assert ll.next.value == 76
assert ll.next.next.value == 12
assert ll.next.next.next.next.next == -1
def test_seek(self):
"""Test seek() functionality."""
ll = LinkedCell(5)
ll = ll.prepend(6)
ll = ll.prepend(12)
ll = ll.prepend(76)
ll = ll.prepend(1)
assert ll.seek(0) == 1
assert ll.seek(1) == 76
assert ll.seek(4) == 5
assert ll.seek(-1) == -1
assert ll.seek(101) == -1
assert ll.seek(5) == -1
def test_len(self):
"""Test len() functionality."""
ll = LinkedCell(5)
ll = ll.prepend(6)
ll = ll.prepend(12)
ll = ll.prepend(76)
ll = ll.prepend(1)
assert ll.len() == 5
assert LinkedCell(9).len() == 1
def main():
"""Try printing functionality."""
ll = LinkedCell(5)
ll = ll.prepend(6)
ll = ll.prepend(12)
ll = ll.prepend(76)
ll = ll.prepend(1)
ll.simple_traverse()
# l2 = LinkedCell(101)
# l2 = l2.prepend(65)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment