Can't remove first node in linked list
Posted
by
carlmonday
on Stack Overflow
See other posts from Stack Overflow
or by carlmonday
Published on 2012-10-26T16:34:38Z
Indexed on
2012/10/26
17:01 UTC
Read the original article
Hit count: 180
I'm trying to make a linked list class in python (pointless I know, but it's a learning exercise), and the method I have written to remove a node doesn't work if I try to remove the first element of the linked list. If the node to be removed is anywhere else in the linked list the method works fine. Can someone give me some insight as to where I've gone wrong?
Here's my code thus far:
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __repr__(self):
return repr(self.data)
def printNodes(self):
while self:
print self.data
self = self.next
def removeNode(self, datum):
"""removes node from linked list"""
if self.data == datum:
return self.next
while self.next:
if self.next.data == datum:
self.next = self.next.next
return self
self = self.next
© Stack Overflow or respective owner