-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcir_linked_list_insert.c
More file actions
102 lines (94 loc) · 2.35 KB
/
cir_linked_list_insert.c
File metadata and controls
102 lines (94 loc) · 2.35 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
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
void traversal(struct Node* head)
{
struct Node* ptr = head;
do
{
printf("%d -> ", ptr->data);
ptr=ptr->next;
} while (ptr!=head);
printf("HEAD");
}
struct Node* insert_at_head(struct Node* head, int value)
{
struct Node* new = (struct Node*) malloc (sizeof(struct Node));
new->data = value;
struct Node* ptr = head;
do
{
ptr=ptr->next;
} while (ptr->next!=head);
ptr->next=new;
new->next=head;
head=new;
return head;
}
struct Node* insert_at_index(struct Node* head, int value, int index)
{
struct Node* new = (struct Node*) malloc (sizeof(struct Node));
new->data = value;
struct Node* ptr = head;
int i=0;
while(i!=index-1)
{
ptr=ptr->next;
i++;
}
new->next = ptr->next;
ptr->next = new;
return head;
}
struct Node* insert_at_end(struct Node* head, int value)
{
struct Node* new=(struct Node*) malloc (sizeof(struct Node));
new->data=value;
struct Node* ptr = head->next;
while(ptr->next!=head)
ptr=ptr->next;
ptr->next = new;
new->next=head;
return head;
}
struct Node* insert_after_node(struct Node* head, struct Node* node, int value)
{
struct Node* new = (struct Node*) malloc (sizeof(struct Node));
new->data=value;
new->next=node->next;
node->next=new;
return head;
}
int main()
{
struct Node* head = (struct Node*) malloc (sizeof(struct Node));
struct Node* second = (struct Node*) malloc (sizeof(struct Node));
struct Node* third = (struct Node*) malloc (sizeof(struct Node));
struct Node* fourth = (struct Node*) malloc (sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = head;
traversal(head);
head = insert_at_head(head, 56);
printf("\n");
traversal(head);
head = insert_at_index(head, 99, 3);
printf("\n");
traversal(head);
head = insert_at_end(head, 100);
printf("\n");
traversal(head);
head = insert_after_node(head, third, 755);
printf("\n");
traversal(head);
return 0;
}