Complete the code to check if a linked list is circular by comparing the next pointer of the last node.
if (lastNode.next == [1]) { System.out.println("List is circular"); } else { System.out.println("List is linear"); }
The last node in a circular linked list points back to the head node, making the list circular.
Complete the code to traverse a circular linked list starting from head and stopping when it loops back.
Node current = head;
do {
System.out.print(current.data + " -> ");
current = current.next;
} while (current != [1]);
System.out.println("null");In a circular linked list, traversal stops when current reaches head again.
Fix the error in the method that checks if a linked list is linear by verifying if any node's next is null.
public boolean isLinear(Node head) {
Node temp = head;
while (temp != null) {
if (temp.next == [1]) {
return true;
}
temp = temp.next;
}
return false;
}In a linear linked list, the last node's next pointer is null.
Fill both blanks to create a method that inserts a new node at the end of a circular linked list.
public void insertEnd(Node newNode) {
if (head == null) {
head = newNode;
newNode.next = [1];
} else {
Node temp = head;
while (temp.next != [2]) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = head;
}
}In a circular linked list, the new node's next points to head, and the last node's next points to the new node.
Fill all three blanks to create a method that converts a linear linked list to a circular linked list by linking last node to head.
public void makeCircular() {
if (head == null) return;
Node temp = head;
while (temp.next != [1]) {
temp = temp.next;
}
temp.next = [2];
System.out.println("List converted to circular starting at " + [3].data);
}The last node's next is null in linear list; to make circular, link it to head. The message prints head's data.
