简体   繁体   中英

Circular Linked list in python

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! :)

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.

enter link description here

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM