Skip to content

Instantly share code, notes, and snippets.

@skrolikowski
Last active January 21, 2019 05:05
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 skrolikowski/ba0880b4a4d7d5d70179d5f53d599e87 to your computer and use it in GitHub Desktop.
Save skrolikowski/ba0880b4a4d7d5d70179d5f53d599e87 to your computer and use it in GitHub Desktop.
Linked List
# Simple Node definition with value and next pointer.
class Node:
def __init__(self, value = 0):
self.value = value
self.next = None
for v in values:
self.add(v)
def __iter__(self):
"""LinkedList iterator operator
Returns:
Iterable
"""
self.node = self
return self
def __next__(self):
"""Returns next Node in iteration.
Returns:
Node
"""
if self.node == None:
raise StopIteration
node = self.node
self.node = self.node.next
return node
def __str__(self):
"""String representation of Node.
Returns:
String
"""
return self.value
# Simple LinkedList definition.
class LinkedList:
def __init__(self, values = []):
self.head = None
self.length = 0
def add(self, value):
"""Add Node to end of LinkedList.
Args:
value(int): new node value
Returns:
Bool
"""
if self.isEmpty():
self.head = ListNode(value)
self.length += 1
else:
curr = self.head
while curr.next != None:
curr = curr.next
curr.next = ListNode(value)
self.length += 1
def length(self):
"""Returns LinkedList length.
Returns:
Bool
"""
return self.length
def isEmpty(self):
"""Is LinkedList empty?.
Returns:
Bool
"""
return self.head == None
def toList(self):
"""Returns List of all Node values in list.
Returns:
List
"""
return [n.val for v in iter(self)]
def __iter__(self):
"""LinkedList iterator operator
Returns:
Iterable
"""
return self.head.__iter__()
def __str__(self):
"""String representation of LinkedList.
Returns:
String
"""
return "->".join([str(n.val) for n in iter(self)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment