Skip to content

Instantly share code, notes, and snippets.

@prologic
Created May 12, 2014 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prologic/a745f94c2ca2dd8bdba1 to your computer and use it in GitHub Desktop.
Save prologic/a745f94c2ca2dd8bdba1 to your computer and use it in GitHub Desktop.
Linked List: In answer to SO http://stackoverflow.com/questions/23601818
#!/usr/bin/env python
class Node(object):
def __init__(self, parent, obj):
self.parent = parent
self.next = None
self.obj = obj
def __repr__(self):
return repr(self.obj)
class LinkedList(object):
"""The simplest Linked List in Python
This is in answer to SO: http://stackoverflow.com/questions/23601818
See: http://en.wikipedia.org/wiki/Linked_list
"""
def __init__(self):
self.size = 0
self.next = None
def __repr__(self):
return "<{0:s} [{1:s}]>".format(
self.__class__.__name__,
", ".join(repr(x) for x in self)
)
def __len__(self):
return self.size
def __iter__(self):
next = self.next
while next is not None:
yield next.obj
next = next.next
def append(self, obj):
self.size += 1
if self.next is None:
self.next = Node(self, obj)
else:
self.next.next = Node(self, obj)
ll = LinkedList()
ll.append(1)
ll.append(2)
print(len(ll))
for x in ll:
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment