Which of the following is the main advantage of using a circular linked list over a singly linked list?
Think about what happens when you reach the end of a singly linked list versus a circular linked list.
A circular linked list connects the last node back to the first node, allowing continuous traversal without restarting from the head. This is useful for applications needing repeated cycles.
What will be the output of the following code that traverses a circular linked list with 3 nodes?
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head) {
struct Node* temp = head;
if (head != NULL) {
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
}
printf("null\n");
}
int main() {
struct Node n1, n2, n3;
n1.data = 1; n2.data = 2; n3.data = 3;
n1.next = &n2; n2.next = &n3; n3.next = &n1;
printList(&n1);
return 0;
}Look at the loop condition in the printList function.
The do-while loop prints nodes until it reaches the head again, so it prints each node once and then stops, printing 'null' at the end.
Which of the following real-world scenarios is best suited for implementing with a circular linked list?
Think about a situation where you want to cycle through items repeatedly without stopping.
A music playlist that repeats songs continuously is a perfect example of a circular linked list because it cycles through songs endlessly.
What is the bug in the following code snippet that inserts a new node at the end of a circular linked list?
void insertEnd(struct Node** head, int data) { struct Node* newNode = malloc(sizeof(struct Node)); newNode->data = data; if (*head == NULL) { *head = newNode; newNode->next = newNode; } else { struct Node* temp = *head; while (temp->next != *head) { temp = temp->next; } temp->next = newNode; newNode->next = *head; } }
Think about how a circular linked list behaves when it has only one node.
In a circular linked list with one node, the node's next pointer should point to itself, not NULL, to maintain the circular structure.
In multiplayer turn-based games, why is a circular linked list often used to manage player turns?
Consider how the game moves from one player to the next repeatedly.
Circular linked lists allow the game to move from the last player back to the first seamlessly, enabling continuous turns without extra logic.
