Complete the code to create a circular linked list node that points to itself.
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = [1];
return newNode;
}In a circular linked list, the node's next pointer points to itself when it is the only node, so newNode->next = newNode; creates a circular link.
Complete the code to traverse a circular linked list starting from head and print all node data once.
void printList(struct Node* head) {
struct Node* temp = head;
if (head == NULL) return;
do {
printf("%d -> ", temp->data);
temp = [1];
} while (temp != head);
printf("NULL\n");
}To move through the circular linked list, we update temp to temp->next in each iteration.
Fix the error in the code to insert a new node after the head in a circular linked list.
void insertAfterHead(struct Node* head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = head->next;
head->next = [1];
}To insert the new node after head, set head->next = newNode; so the head points to the new node.
Fill both blanks to check if a circular linked list is empty or has only one node.
int isSingleNode(struct Node* head) {
if (head == NULL) return 0;
if (head->next == [1] || head->next == [2]) return 1;
return 0;
}For a circular linked list, if head->next == head (only one node), we return 1. The check for NULL is not typical in circular lists as next should never be NULL.
Fill all three blanks to create a function that counts nodes in a circular linked list.
int countNodes(struct Node* head) {
if (head == NULL) return 0;
int count = 1;
struct Node* temp = head->[1];
while (temp != [2]) {
count++;
temp = temp->[3];
}
return count;
}Start from the node after head (head->next), loop until back to head, moving to temp->next each time, counting nodes.
