Circular Linked List traversal in C
Circular Linked List is a type of linked list. It has a special feature which connects the last node to head as a circular format. So the traversal becomes the circular one.
Implementation:
- It starts with declaring the Node structure.
- Next, a function create_Node() is written.
- It allocates the memory. New node’s data is assigned with data. New node’s next is assigned Null.
- To traverse a linked list, from the head to last node, each node is traversed and displayed the data.
- Finally, main() function,nodes are created. The traverse function is called and output is displayed.
C Code:
#include <stdio.h>
#include <stdlib.h>
// Node structure is declared
int data;
struct Node* next;
};
// Let us create a new node
struct Node* create_Node(int data) {
struct Node*
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data =
data;
newNode->next =
NULL;
return newNode;
}
// Traverse a circular linked list
void traverseIt(struct Node* head) {
if (head == NULL)
{
printf("List is empty.\n");
return;
}
struct Node* temp
= head;
do {
printf("%d -> ", temp->data);
temp =
temp->next;
} while (temp !=
head); // Stop when we come back to head
printf("(back
to head)\n");
}
int main() {
// Create nodes
struct Node* head
= create_Node(23);
struct Node*
second = create_Node(40);
struct Node* third
= create_Node(80);
struct Node*
fourth = create_Node(145);
struct Node* fifth
= create_Node(8);
struct Node* sixth
= create_Node(560);
// the Link nodes
in circular linked lsit
head->next =
second;
second->next =
third;
third->next =
fourth;
fourth->next =
fifth;
fifth->next =
sixth;
sixth->next =
head;
traverseIt(head);
}
Output:
23 -> 40 -> 80 -> 145 -> 8 -> 560 -> (back
to head)
Hope, this code is useful to you. This is the easy way of
implementing the traversal of circular linked list. Keep coding!!!
Comments
Post a Comment