-
Notifications
You must be signed in to change notification settings - Fork 72
/
Binary Search on Singly Linked List
92 lines (77 loc) · 1.53 KB
/
Binary Search on Singly Linked List
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
// CPP code to implement binary search
// on Singly Linked List
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
Node *newNode(int x)
{
struct Node* temp = new Node;
temp->data = x;
temp->next = NULL;
return temp;
}
// function to find out middle element
struct Node* middle(Node* start, Node* last)
{
if (start == NULL)
return NULL;
struct Node* slow = start;
struct Node* fast = start -> next;
while (fast != last)
{
fast = fast -> next;
if (fast != last)
{
slow = slow -> next;
fast = fast -> next;
}
}
return slow;
}
// Function for implementing the Binary
// Search on linked list
struct Node* binarySearch(Node *head, int value)
{
struct Node* start = head;
struct Node* last = NULL;
do
{
// Find middle
Node* mid = middle(start, last);
// If middle is empty
if (mid == NULL)
return NULL;
// If value is present at middle
if (mid -> data == value)
return mid;
// If value is more than mid
else if (mid -> data < value)
start = mid -> next;
// If the value is less than mid.
else
last = mid;
} while (last == NULL ||
last != start);
// value not present
return NULL;
}
// Driver Code
int main()
{
Node *head = newNode(1);
head->next = newNode(4);
head->next->next = newNode(7);
head->next->next->next = newNode(8);
head->next->next->next->next = newNode(9);
head->next->next->next->next->next = newNode(10);
int value = 7;
if (binarySearch(head, value) == NULL)
printf("Value not present\n");
else
printf("Present");
return 0;
}