Circular Linked List Traversal in C++ in DSA
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node * next;
};
void display(node* head){
node *temp=head;
if(head!=NULL){
do{
cout<<temp->data<<" ";
temp=temp->next;
}
while(temp!=head);
}
}
void ins(node **head, int p){
node *ptr=new node();
node *temp=*head;
ptr->data=p;
ptr->next=*head;
if(*head!=NULL){
while(temp->next!=*head){
temp=temp->next;
}temp->next=ptr;
}
else{
ptr->next=ptr;
*head=ptr;
}
}
int main() {
node *h=NULL;
int n;
cin>>n;
for(int i=0; i<n; i++){
int temp;
cin>>temp;
ins(&h,temp);
}
display(h);
return 0;
}
0 Comments