-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertlinklist.c
More file actions
78 lines (59 loc) · 1.58 KB
/
Insertlinklist.c
File metadata and controls
78 lines (59 loc) · 1.58 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
// CODE FOR INSERTING IN LINKLIST USING MANUALLY WHEN DECLARED LOCALLY
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void display(struct node *head) // display
{
struct node * ptr;
printf("Link list : ");
for (ptr = head ; ptr != NULL ; ptr = ptr -> next)
{
printf("%d " , ptr -> data);
printf("\n");
}
// printf("\n");
}
void insert(struct node **head,int value , int pos) // for inserting
{
struct node * current , *ptr ;
current = malloc(sizeof(struct node));
current -> data = value;
current -> next = NULL;
if(head == NULL && pos != 0)
printf("Invalid\n");
else if (pos == 0) // inserting at begining
{
current -> next = *head;
*head = current;
}
else // inserting in MIDDLE and end
{
ptr = *head;
for (int i = 0; i < pos - 1 ; i++)
{
ptr = ptr -> next;
if(ptr == NULL)
{
printf("Invalid\n");
return;
}
}
current -> next = ptr -> next;
ptr -> next = current;
}
}
int main() //main function
{
struct node *head = NULL; // locally declare
insert(&head,2,0); //calling of insert function
insert(&head,8,1); //calling of insert function
insert(&head,9,2); //calling of insert function
insert(&head,7,3); //calling of insert function
insert(&head,6,4); //calling of insert function
display(head);
return 0;
}