Skip to content

Instantly share code, notes, and snippets.

@ssundarraj
Last active January 3, 2016 19:02
Show Gist options
  • Save ssundarraj/50ef0d2ba020f159d427 to your computer and use it in GitHub Desktop.
Save ssundarraj/50ef0d2ba020f159d427 to your computer and use it in GitHub Desktop.
python_ds
class LinkedListNode(object):
def __init__(self, data=None, next_node=None):
self.next_node = next_node
self.data = data
class LinkedList(object):
def __init__(self):
self.head = None
def append(self, data):
new_node = LinkedListNode(data, None)
if self.head is None:
self.head = new_node
else:
temp = self.head
while temp.next_node:
temp = temp.next_node
temp.next_node = new_node
def __repr__(self):
# Function for printing the LL in human readable format
temp = self.head
repr_str = ""
while temp:
repr_str += str(temp.data) + " "
temp = temp.next_node
return repr_str
def delete(self, pos):
if pos == 0 and self.head:
del_node = self.head
self.head = self.head.next
return del_node
temp = self.head
try:
for _ in range(pos - 1):
temp = temp.next_node
except AttributeError: # testing if pos > len
raise IndexError("Position greater than length of list")
return
del_node = temp.next_node
temp.next_node = del_node.next_node
return del_node
@mayweed
Copy link

mayweed commented Jan 3, 2016

Just a typo in delete method: if pos==0 after assigning self.head to del_node, the next node becomes the head so: it's not "self.head=self.head.next" but self.head=self.head.next_node

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment