forked from Sai-02/Data-Structures-using-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert_In_a_Sorted_LinkedList.c
78 lines (73 loc) · 1.65 KB
/
Insert_In_a_Sorted_LinkedList.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
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *link;
};
struct node *insertValue(struct node *, int);
void main()
{
int n;
int counter=0;
printf("Enter the size of the linked list:");
scanf("%d", &n);
struct node *head = (struct node *)malloc(sizeof(struct node));
head->link=NULL;
struct node *temp;
for (int i = 0; i < n; i++)
{
counter++;
int value;
printf("\nEnter the value of node:");
scanf("%d", &value);
if (i == 0)
{
head->info = value;
temp = head;
}
else
{
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = value;
new->link=NULL;
temp->link = new;
temp = temp->link;
}
}
int k;
scanf("%d", &k);
head = insertValue(head, k);
temp=head;
// printf("%d",temp->info);
while(temp!=NULL){
printf("%d ",temp->info);
temp=temp->link;
}
printf("The no. of steps took to complete the insertion was %d", counter);
}
struct node *insertValue(struct node *head, int k)
{
struct node *temp = head;
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = k;
new->link=NULL;
if (head->info > k)
{
new->link = head;
head = new;
return head;
}
while (temp->link != NULL)
{
if (temp->link->info > k)
{
new->link = temp->link;
temp->link = new;
return head;
}
temp = temp->link;
}
temp->link=new;
return head;
}