python - Removing a node from a linked list with "del" doesn't work -
the problematic part in function remove
. after del
called, relevant node not removed linked list. did misunderstand del
?
class node: def __init__(self, val): self.val = val self.next = none def add(self, val): if not (self.next): self.next = node(val) else: self.next.add(val) def remove(self, val): if self.val == val: if self.next: self.val = self.next.val self.next = self.next.next else: del self # doesn't remove node linked list else: if self.next: self.next.remove(val) else: print "no such val found %d" % val def __str__(self): output = [] while self not none: output.append(str(self.val)) self = self.next return " -> ".join(output) head = node(1) head.add(2) print head head.remove(3) head.add(3) head.add(4) print head head.remove(3) head.remove(4) print head
the statement del self
removes name self
local scope (and decrements reference count). has no effect on other references nor objects.
to remove node linked list, must update node(s) refer it. since have singly linked list, must traverse list beginning find node node.next == self
, change node.next = self.next
remove self sequence of links.
Comments
Post a Comment