-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert_ascending_order.c
114 lines (103 loc) · 2.15 KB
/
insert_ascending_order.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
110
111
112
113
114
//24->45->56->100
#include<stdio.h>
#include<stdlib.h>
//creating node
struct node
{
int info;
struct node *link;
};
struct node *first(struct node *s,int a)
{
s=malloc(sizeof(struct node));
s->info=a;
s->link=NULL;
return s;
}
void add_end(struct node **s,int a)
{
struct node *new=malloc(sizeof(struct node));
new->info=a;
new->link=NULL;
struct node *tmp=*s;
while((tmp->link)!=NULL)
{
tmp=tmp->link;
}
tmp->link=new;
}
void insert(struct node **s,int a)
{
// struct node *new=malloc(sizeof(struct node));
// new->info=a;
// new->link=NULL;
// struct node *tmp=*s;
// struct node *tmp2=NULL;
// if( a<(tmp->info))//to insert node in the beginning
// {
// new->link=tmp;
// tmp=new;
// }
// else
// {
// while((tmp->info)<=a)
// {
// tmp2=tmp;
// tmp=tmp->link;
// }
// new->link=tmp;//new->link=tmp2->link
// tmp2->link=new;
// }
struct node *new=malloc(sizeof(struct node));
new->info=a;
new->link=NULL;
struct node *tmp=*s;
if(((*s)->info)>a)//to add in the beginning of the linked list
{
printf("entered loop");
new->link=*s;
*s=new;
return ;
}
else
{
while(tmp->link!=NULL && (tmp->link->info)<=a )
{
//tmp2=tmp;
tmp=tmp->link;
}
new->link=tmp->link;
tmp->link=new;
}
}
void display(struct node *s)
{
struct node *tmp=s;
while(tmp!=NULL)
{
printf("%d\n",tmp->info);
tmp=tmp->link;
}
};
int main()
{
int d;
printf("enter an element to insert in between");
scanf("%d",&d);
struct node *head;
head=first(head,24);
display(head);
printf("--\n");
add_end(&head,45);
printf("--\n");
display(head);
add_end(&head,56);
printf("--\n");
display(head);
add_end(&head,100);
printf("--\n");
display(head);
insert(&head,d);
printf("--\n");
display(head);
}