-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertnode.c
More file actions
54 lines (50 loc) · 1.27 KB
/
insertnode.c
File metadata and controls
54 lines (50 loc) · 1.27 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
#include<stdio.h>
#include<stdlib.h>
//declaration of node
struct node{
int data ;
struct node *next;
};
void traversal(struct node *ptr);
struct node * insertatfirst(struct node *head,int data);
struct node *insertatmid(struct node *head,int data, int index);
int main(){
struct node *head = (struct node * )malloc(sizeof(struct node));
struct node *second = (struct node * )malloc(sizeof(struct node));
head-> data = 5;
head-> next = second;
second->data = 6;
second->next = NULL;
traversal(head);
printf("\n");
head = insertatfirst(head,4);
traversal(head);
insertatmid(head,7,2);
printf("\n");
traversal(head);
return 0;
}
void traversal(struct node *ptr){
while(ptr!=NULL){
printf("%d\t",ptr->data);
ptr = ptr->next;
}
}
struct node *insertatfirst(struct node *head, int data){
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
ptr->next = head;
return ptr;
}
struct node *insertatmid(struct node *head,int data, int index){
struct node *ptr = (struct node *)malloc(sizeof(struct node));
struct node *p = head;
int i=0;
while(i!=index-1){
p = p -> next;
i++;
}
ptr->data = data;
ptr->next = p->next;
p->next = ptr;
}