Didn’t getting deired output in Circular Singly Linked List whille inserting the nodes

  data-structures, oop, python, singly-linked-list

I’m not able to get the desired output in the given code. The code is about inserting nodes in the circular singly linked list. Please correct this code as per the problems stated.

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
 
class CircularSLL:
    
    def __init__(self):
        self.head = None
        self.tail = None
        
    def __iter__(self):
        node = self.head
        while node:
            yield node
            if node.next == self.head:
                print('break')
                break
            node = node.next
            
    def insertnode(self, value, location):
        new_node = Node(value)
        
        # check if head is None or not
        
        if self.head is None:
            self.head = new_node
            self.tail = new_node
            new_node.next = self.head
            
        else:
            
            
            
            # At the start
            if location == 0:
                new_node.next = self.head
                self.head = new_node
                self.tail.next = self.head
            
            # At the end
            elif location == -1:
                new_node.next = self.tail.next
                self.tail.next = new_node
                self.tail = new_node
                
            else:
                
                # At specific location
                temp_node = self.head
                index = 0
                
                while index < location - 1:
                    
                    # next node is the last element
                    if temp_node.next == self.head:
                        new_node.next = self.head
                    temp_node = temp_node.next
                    index += 1
                
                next_node = temp_node.next
                temp_node.next = new_node
                new_node.next = next_node
                
                # if location > len
                if temp_node.next == self.head:
                    self.tail == temp_node
                    self.tail.next = self.head
                
            return 'The node has been successfully inserted'
 
cll = CircularSLL()
 
cll.insertnode(1,0)
 
cll.insertnode(3, 1)
 
cll.insertnode(4, 2)
 
cll.insertnode(5, 3)
 
cll.insertnode(6, 4)
 
print([node.value for node in call]) 

output = [1,3,4,5,6 ]

1st problem – when inserting at index = ‘0’.

cll.insertnode(10,0)

output = [10,1]

expected

output = [10,1,3,4,5,6]

2nd problem – when inserting at index > len

cll.insertnode(30, -1)

output = [1, 3, 4, 5, 20, 6, 7]

expected

output = [10,1,3,4,5,6,20]

3rd problem(same as 2nd) – but location = ‘-1’

cll.insertnode(30, -1)

output = [1, 30, 3, 4, 5, 20, 6, 7]

expected

output = [10,1,3,4,5,6,20,30]

Source: Python Questions

LEAVE A COMMENT