Oscar Dolloway Oscar Dolloway - 12 days ago 5
Python Question

Linked-list node delete function

I've been asked to implement a Node delete function

So far I can add nodes to the list and display them just stuck on the deleting a node part.

class Node(object):
def __init__(self, value):
self.value=value
self.next=None
self.prev=None

class List(object):
def __init__(self):
self.head=None
self.tail=None

def insert(self,n,x):
if n!=None:
x.next=n.next
n.next=x
x.prev=n
if x.next!=None:
x.next.prev=x
if self.head==None:
self.head=self.tail=x
x.prev=x.next=None
elif self.tail==n:
self.tail=x

def display(self):
values=[]
n=self.head
while n!=None:
values.append(str(n.value))
n=n.next
print ("List: ",",".join(values))

def deleteNode (self,n):
if n.prev!=None:
n.prev.next = n.next
else:
self.head = n.next

if n.next != None:
n.next.prev = n.prev
else:
self.tail = n.prev

if __name__ == '__main__':
listofnodes=List()
listofnodes.insert(None, Node(4))
listofnodes.insert(l.tail,Node(6))
listofnodes.insert(l.head,Node(8))
listofnodes.insert(l.head,Node(5))
listofnodes.insert(l.head,Node(9))
listofnodes.insert(l.head,Node(10))
listofnodes.deleteNode(l,Node(8)) # I want to delete Node 8 from listofnodes
listofnodes.display()


This may be a basic error but I when I run the code it generates a
TypeError
:

TypeError: deleteNode() takes 2 positional arguments but 3 were given

Answer

In

listofnodes.deleteNode(l,Node(8))

you are passing 2 argument, with a third one (the self in the declaration) passed implicitly

You declare the method as

def deleteNode (self,n):

so it accept only one parameter (n)