Skip to content

Commit e3d26b9

Browse files
authored
Circular Linked List Traversal.cpp
1 parent 8658e9a commit e3d26b9

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
4+
struct Node
5+
{
6+
int data;
7+
struct Node *next;
8+
};
9+
10+
void push(struct Node **head_ref, int data)
11+
{
12+
struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));
13+
struct Node *temp = *head_ref;
14+
ptr1->data = data;
15+
ptr1->next = *head_ref;
16+
17+
if (*head_ref != NULL)
18+
{
19+
while (temp->next != *head_ref)
20+
temp = temp->next;
21+
temp->next = ptr1;
22+
}
23+
else
24+
ptr1->next = ptr1;
25+
26+
*head_ref = ptr1;
27+
}
28+
29+
void printList(struct Node*);
30+
31+
int main()
32+
{
33+
int i,n,t,val;
34+
scanf("%d",&t);
35+
36+
while(t--)
37+
{
38+
struct Node *head = NULL;
39+
scanf("%d",&n);
40+
for(i=0;i<n;i++)
41+
{
42+
scanf("%d",&val);
43+
push(&head,val);
44+
}
45+
printList(head);
46+
printf("\n");
47+
}
48+
return 0;
49+
}
50+
// } Driver Code Ends
51+
52+
53+
/* structure for a node
54+
struct Node
55+
{
56+
int data;
57+
struct Node *next;
58+
}; */
59+
60+
/* Function to print nodes in a given Circular linked list */
61+
void printList(struct Node *head)
62+
{
63+
// code here
64+
if(head==NULL)
65+
return;
66+
printf("%d ",head->data);
67+
68+
struct Node *cur=head->next;
69+
70+
71+
while(cur!=head)
72+
{
73+
printf("%d ",cur->data);
74+
cur=cur->next;
75+
76+
}
77+
78+
}

0 commit comments

Comments
 (0)