-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular_linked_insert.c
More file actions
108 lines (88 loc) · 2.03 KB
/
circular_linked_insert.c
File metadata and controls
108 lines (88 loc) · 2.03 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *next;
int data;
};
void traversal(struct node *head)
{
struct node *ptr = head;
do
{
printf("Element : %d\n", ptr->data);
ptr = ptr->next;
} while (ptr != head);
}
struct node *insertatfirst(struct node *head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
struct node *p = head->next;
while (p->next != head)
{
p = p->next;
}
p->next = ptr;
ptr->next = head;
head = ptr;
return head;
};
struct node *insertatend(struct node *head, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
struct node *p = head->next;
while (p->next != head)
{
p = p->next;
}
p->next = ptr;
ptr->next = head;
return head;
};
struct node *insertatindex(struct node *head, int index, int data)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
struct node *p = head->next;
int i = 0;
while (i != index - 2)
{
p = p->next;
i++;
}
ptr->data = data;
ptr->next = p->next;
p->next = ptr;
return head;
}
int main()
{
struct node *head;
struct node *second;
struct node *third;
struct node *fourth;
head = (struct node *)malloc(sizeof(struct node));
second = (struct node *)malloc(sizeof(struct node));
third = (struct node *)malloc(sizeof(struct node));
fourth = (struct node *)malloc(sizeof(struct node));
head->data = 90;
head->next = second;
second->data = 35;
second->next = third;
third->data = 42;
third->next = fourth;
fourth->data = 53;
fourth->next = head;
traversal(head);
printf("After insertion :\n");
head = insertatfirst(head, 46);
traversal(head);
printf("After insertion :\n");
insertatend(head, 54);
traversal(head);
printf("After insertion :\n");
insertatindex(head, 2, 66);
traversal(head);
return 0;
}