在C ++中对单链表的二进制搜索

一个单向链表是一个链表(数据结构存储节点的值和下一个节点的内存位置),它可以去只有一条路。

二进制搜索是一种基于划分和规则的搜索算法。这样就可以找到结构的中间元素,并针对不等式比较并使用递归调用同一算法。

在这里,我们得到一个单链表和一个使用二分查找法找到的元素。

由于单链列表是仅使用一个指针的数据结构,因此很难找到其中间元素。在单链列表的中间,我们使用两种指针方法。

算法

Step 1 : Initialize, start_node (head of list) and last_node (will have last value) , mid_node (middle node of the structure).
Step 2 : Compare mid_node to element
   Step 2.1 : if mid_node = element, return value “found”.
   Step 2.2 : if mid_node > element, call binary search on lower_Half.
   Step 2.3 : if mid_node < element, call binary search on upper_Half.
Step 3 : if entire list is traversed, return “Not found”.

示例

#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;
}
struct Node* mid_node(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;
}
struct Node* binarySearch(Node *head, int value){
   struct Node* start = head;
   struct Node* last = NULL;
   do{
      Node* mid = mid_node(start, last);
      if (mid == NULL)
         return NULL;
      if (mid -> data == value)
         return mid;
      else if (mid -> data < value)
         start = mid -> next;
      else
         last = mid;
   }
   while (last == NULL || last != start);
      return NULL;
}
int main(){
   Node *head = newNode(54);
   head->next = newNode(12);
   head->next->next = newNode(18);
   head->next->next->next = newNode(23);
   head->next->next->next->next = newNode(52);
   head->next->next->next->next->next = newNode(76);
   int value = 52;
   if (binarySearch(head, value) == NULL)
      printf("Value is not present in linked list\n");
   else
      printf("The value is present in linked list\n");
   return 0;
}

输出结果

The value is present in linked list