forked from Sai-02/Data-Structures-using-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearching_in_Sorted_linked_list.c
61 lines (59 loc) · 1.26 KB
/
Searching_in_Sorted_linked_list.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
#include <stdio.h>
#include <stdlib.h>
//Create a structure of node
struct node
{
int info;
struct node *link;
};
int searchValue(struct node *, int);
int main()
{
int n;
scanf("%d", &n);
struct node *head = (struct node *)malloc(sizeof(struct node));// Base Node
struct node *temp;
// Program for Create/Insertion insertion in Linked List by Sorted Form
for (int i = 0; i < n; i++)
{
int value;
scanf("%d", &value);
if (i == 0)
{
head->info = value;
temp = head;
}
else
{
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = value;
temp->link = new;
temp = temp->link;
}
}
int k;
scanf("%d", &k);
int position = searchValue(head, k);// Search Value
printf("%d", position);
return 0;
}
//Program For Search Value in Sorted Linked List
int searchValue(struct node *head, int k)
{
struct node *temp = head;
int i = 1;
while (temp != NULL)
{
if (temp->info > k)
{
return -1;
}
else if (temp->info == k)
{
return i;
}
temp = temp->link;
i++;
}
return -1;
}