In Circular Linked list any node can be the starting point.
The last node points to the head node. It can be used in understanding queue but we only have to maintain a single pointer rather than two pointers front & rear. It can be used where there is a need to repeat a sequence like CPU jobs.
To traverse the Linked list we have to change the condition from temp!=NULL to temp!=head. We are using do while loop so the temp pointer will be at next node while checking the condition temp!=head.
If we don’t make the changes the code will execute infinitely.
/*C code to implement Circular Linked List */ #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } NODE; NODE *head = NULL; NODE *newNode(int key) { NODE *temp = (NODE *)malloc(sizeof(NODE)); temp->data = key; temp->next = NULL; return temp; } void printList() { NODE *temp = head; if (temp == NULL) { printf("List is empty!\n"); return; } printf("Circular Linked List is\t"); do { printf("%d ", temp->data); temp = temp->next; } while (temp != head); printf("\n"); } int main() { head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = head; printList(); return 0; }
$ ./a.out Circular Linked List is 1 2 3 4 5 $ |
also see
C Programming language |
Go Programming language |
Linked List | Array |
Simplification | Queue |
DBMS | Reasoning |
Aptitude | HTML |