-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinsert_linklist.c
109 lines (100 loc) · 2.51 KB
/
insert_linklist.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
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
109
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *createlinklist(int n);
void display(struct node *head);
struct node * insertAt1st(struct node *head,int data);
struct node * insertAtlast(struct node *head,int data);
struct node *insertAtIndex(struct node *head, int data, int index);
int main()
{
int n;
struct node *head = NULL;
printf("Enter how many nodes: ");
scanf("%d", &n);
head = createlinklist(n);
display(head);
head=insertAt1st(head,5);
head=insertAtlast(head,65);
head=insertAtIndex(head,25,2);
printf("\n");
display(head);
return 0;
}
struct node *createlinklist(int n)
{
struct node *head = NULL;
struct node *temp = NULL;
struct node *p = NULL;
for (int i = 0; i < n; i++)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->next = NULL;
printf("Enter data: ");
scanf("%d", &temp->data);
if (head == NULL)
{
head = temp;
}
else
{
p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
}
}
return head;
}
struct node * insertAt1st(struct node *head,int data){
struct node* insertenNode = NULL;
insertenNode = (struct node *)malloc(sizeof(struct node));
insertenNode->data=data;
insertenNode->next=head;
head=insertenNode;
return head;
}
void display(struct node *head)
{
struct node *p = head;
while (p != NULL)
{
printf("%d->", p->data);
p = p->next;
}
printf("NULL");
}
struct node * insertAtlast(struct node *head,int data){
struct node* insertenNode = NULL;
insertenNode = (struct node *)malloc(sizeof(struct node));
insertenNode->data=data;
struct node *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next=insertenNode;
insertenNode->next=NULL;
return head;
}
struct node *insertAtIndex(struct node *head, int data, int index)
{
struct node *NewNode = (struct node *)malloc(sizeof(struct node));
struct node *p = head;
int i = 0;
while (i != index - 1)
{
p = p->next;
i++;
}
NewNode->data = data;
NewNode->next = p->next;
p->next = NewNode;
return head;
}