A circular linked list, is a linked list whose last node links back to the first
ID: 3771773 • Letter: A
Question
A circular linked list, is a linked list whose last node links back to the first node (as opposed to null). Consider a circular linked list which maintains integers (> 0) in sorted order, and always contains exactly one node with the value of 0. The code for the Node class, a main method using it, and a picture of the list after the main is executed are given below. public class Node { int value; Node next; public Node (int v) { value = v; next = null; } } public static void main (string [] args) { Node head = new Node (0); head. next = head; insertValue (head, 5); insertValue (head, 3); insertValue (head, 4); } Implement the insertValue method (used in the main method) to insert a new value into the correct position in the list. This method should use a loop, not recursion. public static void insertValue (Node n, int x)Explanation / Answer
public static void insertValue(Node n, int x)
{
Node temp = n;
while(temp.next.value!=0 && temp.next.value<x)
{
temp = temp.next;
}
Node new_node = new Node(x);
new_node.next = temp.next;
temp.next=new_node;
}
Recursive Implementation
public static void insertValue(Node n, int x)
{
if(n.next.value==0 || n.next.value >=x)
{
Node new_node = new Node(x);
new_node.next = n.next;
n.next=new_node;
}
else
{
insertValue(n.next,x);
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.