Skip to content

Instantly share code, notes, and snippets.

@rafiamafia
Created February 20, 2018 01:45
Show Gist options
  • Save rafiamafia/4eb37092b71d693e5e59cc30909cf230 to your computer and use it in GitHub Desktop.
Save rafiamafia/4eb37092b71d693e5e59cc30909cf230 to your computer and use it in GitHub Desktop.
Python3 Linked List implementation
class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
def __str__ (self):
return str(self.data)
class PyLinkedList:
def __init__(self):
# TODO: create a new node in the constructor
self._head = None
self._size = 0
def size(self):
return self._size
def add(self, data):
node = Node(data, self._head)
self._head = node
self._size += 1
def remove(self, data):
current = self._head
prev = None
while current:
if current.data == data:
if current == self._head:
self._head = current.next
else:
prev.next = current.next
self._size -= 1
return current
else:
prev = current
current = current.next
return ValueError("{} does not exist in the linked list".format(data))
def find(self, data):
current = self._head
while current:
if current.data == data:
return current
current = current.next
return ValueError("{} does not exist in the linked list".format(data))
def __repr__(self):
return "[{}]".format(", ".join(map(str, self)))
def __iter__(self):
current = self._head
while current:
yield current
current = current.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment