-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q2_CircularLL.c
61 lines (55 loc) · 1.24 KB
/
Q2_CircularLL.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 5.2 Write a program to create a circular linked list and display the elements of the list.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *construct(int data) {
Node *this = (Node *) malloc(sizeof(Node));
if (this != NULL) {
this->data = data;
this->next = NULL;
}
return this;
}
void append(Node **this, int data) {
Node *newNode = construct(data);
if (*this == NULL) {
*this = newNode;
newNode->next = *this;
return;
}
Node *current = *this;
while (current->next != *this) {
current = current->next;
}
current->next = newNode;
newNode->next = *this;
}
void display(Node *this) {
if (this == NULL) {
printf("Circular linked list is empty.\n");
return;
}
Node *ptr = this;
do {
printf("%d -> ", ptr->data);
ptr = ptr->next;
} while (ptr != this);
printf("\n");
}
int main() {
int n;
printf("Enter number of nodes: ");
scanf("%d", &n);
Node *head = NULL;
int elem;
printf("Enter elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &elem);
append(&head, elem);
}
display(head);
return 0;
}