I want to add a given data into an already sorted Circular Linked List such that the resultant list is also sorted. The class for the Node is already provided which have public int data and public Node next as the class members.
A function addNode(Node head) is to be implemented which will insert a known data(9) into the list. Node head is the head pointer of the circular linked list.
I have considered the following cases
When the list is empty, create the Node, put its data as 9 and refer its next to itself. Make the newly created node as the head.
When the list contains only one item. Modify the first node's next pointer to point to the new node and new node's next pointer to the given head node. Make the head node point to the node whose value is the lowest.
When the inserted data is the smallest among all i.e it will be smaller than the data of the node which the head node points to and it will be inserted before the Head node.
When the data is to be inserted between two nodes. So I am using the while loop which will find the node before which the new data will be inserted and modifying the node's next pointer accordingly.
When I am submitting the code, it is somehow failing one test case which I am not able to find out. Can someone help me in finding out the condition that I might be overlooking in my logic.
Below is the implemented code:
public static Node addElement(Node input1)
{
//Write code here
Node result = new Node();
Node current = new Node();
current = input1;
Node value = new Node();
value.data = 10;
if(current == null){
value.next = value;
result = value;
}
else if(current.next == current){
value.next = input1;
current.next = value;
result = current.data < value.data ? current : value;
}
else if(value.data < current.data){
while(current.next != input1)
current = current.next;
current.next = value;
current.next.next = input1;
result = current.next;
}
else{
while(current.next != input1 && current.next.data <= value.data)
current = current.next;
Node currentNext = current.next;
current.next = value;
current.next.next = currentNext;
result = input1;
}
return result;
}
input1is supposed to be thehead node. - Sebastian_H9or10? If the order is examined or the list checked for a specific number, the test might fail. Otherwise I can't see a problem. - Sebastian_H