Circular Linked List Traversal
In a conventional linked list, i.e singly linked list we traverse the list from the starting node and stop traversing it till we reach the last node. The last node in the singly linked list is identified as a node which has NULL next to it. In a circular linked list, we stop traversal when we reach the first node again.
Following is C++ code for linked list traversal.
[code language=”language”]
void print_circular_linked_list( struct node* head)
{
struct node* current = head;
cout<<curr->data;
curr=curr->next;
while(curr->data != head->data)
{
cout<<curr->data;
curr=curr->next;
}
}
[/code]
Below mentioned is the complete program for complete linked list traversal.
Readers are requested to submit their self- written codes in different languages in the comment section below. Best codes will be published on this page.
[code language=”cpp”]
#include<stdio.h>
#include<stdlib.h>
#include<bits/stdc++.h>
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);
}
}
int main()
{
struct Node *head = NULL;
int i,k;
cin>>n;// number of elements in linked list
for( i=0;i<n;i++)
{
struct node* newnode= (struct node*)malloc(sizeof(struct node));
cin>>k;
newnode->data= k;
newnode->next = NULL;
if(i!=0)
prev->next=newnode;
else
head=newnode;
prev= newnode;
}
printf("Contents of Circular Linked List\n ");
printList(head);
return 0;
}
[/code]
Login/Signup to comment