Reputation: 85
def delete_node(head, value):
p=head
if p is None:
return None
while p.value!=value:
p=p.next
if p.next is head and p.value!=value:
return head
p.value=p.next.value
if p.next==head:
head=p
p.next=p.next.next
return head
The above is my code for deleting a node in a circular linked list based on value of the node! The code doesn't gimme result for this case-- I've only 1 element in the list and i deleted it.. So the resultant should be an empty set.. But because i took p.value=p.next.value it points back again to itself and the same value is in the list! Can anyone help me out! Thanx in advance! :)
Upvotes: 1
Views: 1660
Reputation: 13
class node:
def __init__(self, data):
self.data = data
self.next = None
class circularLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insertNode(self, data):
newnode = node(data)
if self.tail is None:
self.head = self.tail = newnode
else:
newnode.next = self.head
self.tail.next = newnode
self.tail = self.tail.next
def printCLL(self):
head = self.head
tail = self.tail
while head.next is not None and head.next is not tail:
print(head.data, end="---")
head = head.next
print(head.data, end="---")
print(tail.data)
c = circularLinkedList()
c.insertNode(1)
c.insertNode(1)
c.insertNode(3)
c.insertNode(4)
c.insertNode(5)
c.printCLL()
Upvotes: -1
Reputation: 30216
The easiest solution here is to have a dummy node that points to itself in case of an empty list. As a consequence in an empty list we have one node that points to itself (the dummy), in a list with one element the dummy points to the element and the element points to the dummy.
Avoids the need for any special cases and generally simplifies the code. To check if the list is empty you can then just do dummy.next is dummy
, also nice.
Upvotes: 2