Binary search on doubly linked list

Given a Doubly linked list[DLL] containing N nodes and an integer X, the task is to find the position of the integer X in the doubly linked list. If no such position found then print -1.

Examples:

Input: 15 <=> 16 <=> 8 <=> 7 <=> 13, X = 8
Output: 3
Explanation: X [= 8] is present at the 3rd node of the doubly linked list.
Therefore, the required output is 3

Input: 5 <=> 3 <=> 4 <=> 2 <=> 9, X = 0
Output: -1
Explanation: X [= 0] is not present in the doubly linked list.
Therefore, the required output is -1



Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Follow the steps below to solve the problem:

  • Initialize a variable, say pos, to store the position of the node containing data value X in the doubly linked list.
  • Initialize a pointer, say temp, to store the head node of the doubly linked list.
  • Iterate over the linked list and for every node, check if data value of that node is equal to X or not. If found to be true, then print pos.
  • Otherwise, print -1.

Below is the implementation of the above approach

C++

// C++ program to implement

// the above approach

#include <bits/stdc++.h>

using namespace std;

// Structure of a node of

// the doubly linked list

struct Node {

// Stores data value

// of a node

int data;

// Stores pointer

// to next node

Node* next;

// Stores pointer

// to previous node

Node* prev;

};

// Function to insert a node at the

// beginning of the Doubly Linked List

void push[Node** head_ref, int new_data]

{

// Allocate memory for new node

Node* new_node

= [Node*]malloc[sizeof[struct Node]];

// Insert the data

new_node->data = new_data;

// Since node is added at the

// beginning, prev is always NULL

new_node->prev = NULL;

// Link the old list to the new node

new_node->next = [*head_ref];

// If pointer to head is not NULL

if [[*head_ref] != NULL] {

// Change the prev of head

// node to new node

[*head_ref]->prev = new_node;

}

// Move the head to point to the new node

[*head_ref] = new_node;

}

// Function to find the position of

// an integer in doubly linked list

int search[Node** head_ref, int x]

{

// Stores head Node

Node* temp = *head_ref;

// Stores position of the integer

// in the doubly linked list

int pos = 0;

// Traverse the doubly linked list

while [temp->data != x

&& temp->next != NULL] {

// Update pos

pos++;

// Update temp

temp = temp->next;

}

// If the integer not present

// in the doubly linked list

if [temp->data != x]

return -1;

// If the integer present in

// the doubly linked list

return [pos + 1];

}

// Driver Code

int main[]

{

Node* head = NULL;

int X = 8;

// Create the doubly linked list

// 18 <-> 15 <-> 8 <-> 9 <-> 14

push[&head, 14];

push[&head, 9];

push[&head, 8];

push[&head, 15];

push[&head, 18];

cout << search[&head, X];

return 0;

}

Java

// Java program to implement

// the above approach

import java.util.*;

class GFG

{

// Structure of a node of

// the doubly linked list

static class Node

{

// Stores data value

// of a node

int data;

// Stores pointer

// to next node

Node next;

// Stores pointer

// to previous node

Node prev;

};

// Function to insert a node at the

// beginning of the Doubly Linked List

static Node push[Node head_ref, int new_data]

{

// Allocate memory for new node

Node new_node = new Node[];

// Insert the data

new_node.data = new_data;

// Since node is added at the

// beginning, prev is always null

new_node.prev = null;

// Link the old list to the new node

new_node.next = head_ref;

// If pointer to head is not null

if [head_ref != null]

{

// Change the prev of head

// node to new node

head_ref.prev = new_node;

}

// Move the head to point to the new node

head_ref = new_node;

return head_ref;

}

// Function to find the position of

// an integer in doubly linked list

static int search[Node head_ref, int x]

{

// Stores head Node

Node temp = head_ref;

// Stores position of the integer

// in the doubly linked list

int pos = 0;

// Traverse the doubly linked list

while [temp.data != x

&& temp.next != null]

{

// Update pos

pos++;

// Update temp

temp = temp.next;

}

// If the integer not present

// in the doubly linked list

if [temp.data != x]

return -1;

// If the integer present in

// the doubly linked list

return [pos + 1];

}

// Driver Code

public static void main[String[] args]

{

Node head = null;

int X = 8;

// Create the doubly linked list

// 18 <-> 15 <-> 8 <-> 9 <-> 14

head = push[head, 14];

head = push[head, 9];

head = push[head, 8];

head = push[head, 15];

head = push[head, 18];

System.out.print[search[head, X]];

}

}

// This code is contributed by Rajput-Ji

C#

// C# program to implement

// the above approach

using System;

class GFG{

// Structure of a node of

// the doubly linked list

public class Node

{

// Stores data value

// of a node

public int data;

// Stores pointer

// to next node

public Node next;

// Stores pointer

// to previous node

public Node prev;

};

// Function to insert a node at the

// beginning of the Doubly Linked List

static Node push[Node head_ref, int new_data]

{

// Allocate memory for new node

Node new_node = new Node[];

// Insert the data

new_node.data = new_data;

// Since node is added at the

// beginning, prev is always null

new_node.prev = null;

// Link the old list to the new node

new_node.next = head_ref;

// If pointer to head is not null

if [head_ref != null]

{

// Change the prev of head

// node to new node

head_ref.prev = new_node;

}

// Move the head to point to the new node

head_ref = new_node;

return head_ref;

}

// Function to find the position of

// an integer in doubly linked list

static int search[Node head_ref, int x]

{

// Stores head Node

Node temp = head_ref;

// Stores position of the integer

// in the doubly linked list

int pos = 0;

// Traverse the doubly linked list

while [temp.data != x &&

temp.next != null]

{

// Update pos

pos++;

// Update temp

temp = temp.next;

}

// If the integer not present

// in the doubly linked list

if [temp.data != x]

return -1;

// If the integer present in

// the doubly linked list

return [pos + 1];

}

// Driver Code

public static void Main[String[] args]

{

Node head = null;

int X = 8;

// Create the doubly linked list

// 18 <-> 15 <-> 8 <-> 9 <-> 14

head = push[head, 14];

head = push[head, 9];

head = push[head, 8];

head = push[head, 15];

head = push[head, 18];

Console.Write[search[head, X]];

}

}

// This code is contributed by gauravrajput1

Javascript

<script>

// Javascript program to implement

// the above approach

// Structure of a node of

// the doubly linked list

class Node {

constructor[]

{

// Stores data value

// of a node

this.data = 0;

// Stores pointer

// to next node

this.next = null;

// Stores pointer

// to previous node

this.prev = null;

}

};

// Function to insert a node at the

// beginning of the Doubly Linked List

function push[head_ref, new_data]

{

// Allocate memory for new node

var new_node

= new Node[];

// Insert the data

new_node.data = new_data;

// Since node is added at the

// beginning, prev is always null

new_node.prev = null;

// Link the old list to the new node

new_node.next = [head_ref];

// If pointer to head is not null

if [[head_ref] != null] {

// Change the prev of head

// node to new node

[head_ref].prev = new_node;

}

// Move the head to point to the new node

[head_ref] = new_node;

return head_ref;

}

// Function to find the position of

// an integer in doubly linked list

function search[ head_ref, x]

{

// Stores head Node

var temp = head_ref;

// Stores position of the integer

// in the doubly linked list

var pos = 0;

// Traverse the doubly linked list

while [temp.data != x

&& temp.next != null] {

// Update pos

pos++;

// Update temp

temp = temp.next;

}

// If the integer not present

// in the doubly linked list

if [temp.data != x]

return -1;

// If the integer present in

// the doubly linked list

return [pos + 1];

}

// Driver Code

var head = null;

var X = 8;

// Create the doubly linked list

// 18 <. 15 <. 8 <. 9 <. 14

head = push[head, 14];

head = push[head, 9];

head = push[head, 8];

head = push[head, 15];

head = push[head, 18];

document.write[ search[head, X]];

// This code is contributed by rrrtnx.

</script>

Python3

# Python program to implement

# the above approach

# Structure of a Node of

# the doubly linked list

class Node:

def __init__[self]:

self.data = 0;

self.next = None;

self.prev = None;

# Function to insert a Node at the

# beginning of the Doubly Linked List

def push[head_ref, new_data]:

# Allocate memory for new Node

new_Node = Node[];

# Insert the data

new_Node.data = new_data;

# Since Node is added at the

# beginning, prev is always None

new_Node.prev = None;

# Link the old list to the new Node

new_Node.next = head_ref;

# If pointer to head is not None

if [head_ref != None]:

# Change the prev of head

# Node to new Node

head_ref.prev = new_Node;

# Move the head to poto the new Node

head_ref = new_Node;

return head_ref;

# Function to find the position of

# an integer in doubly linked list

def search[head_ref, x]:

# Stores head Node

temp = head_ref;

# Stores position of the integer

# in the doubly linked list

pos = 0;

# Traverse the doubly linked list

while [temp.data != x and temp.next != None]:

# Update pos

pos+=1;

# Update temp

temp = temp.next;

# If the integer not present

# in the doubly linked list

if [temp.data != x]:

return -1;

# If the integer present in

# the doubly linked list

return [pos + 1];

# Driver Code

if __name__ == '__main__':

head = None;

X = 8;

# Create the doubly linked list

# 18 <-> 15 <-> 8 <-> 9 <-> 14

head = push[head, 14];

head = push[head, 9];

head = push[head, 8];

head = push[head, 15];

head = push[head, 18];

print[search[head, X]];

# This code is contributed by Rajput-Ji

Output: 3

Time Complexity: O[N]
Auxiliary Space: O[1]


Article Tags :

Linked List

Searching

Technical Scripter

Algorithms-Searching

doubly linked list

Technical Scripter 2020

Practice Tags :

Linked List

Searching

Read Full Article

Given a singly linked list and a key, find key using binary search approach.To perform a Binary search based on Divide and Conquer Algorithm, determination of the middle element is important. Binary Search is usually fast and efficient for arrays because accessing the middle index between two given indices is easy and fast[Time Complexity O[1]]. But memory allocation for the singly linked list is dynamic and non-contiguous, which makes finding the middle element difficult. One approach could be of using skip list, one could be traversing the linked list using one pointer.

Prerequisite: Finding middle of a linked list.


Note: The approach and implementation provided below are to show how Binary Search can be implemented on a linked list. The implementation takes O[n] time.
Approach :

  • Here, start node[set to Head of list], and the last node[set to NULL initially] are given.
  • Middle is calculated using two pointers approach.
  • If middle’s data matches the required value of search, return it.
  • Else if middle’s data < value, move to upper half[setting start to middle’s next].
  • Else go to lower half[setting last to middle].
  • The condition to come out is, either element found or entire list is traversed. When entire list is traversed, last points to start i.e. last -> next == start.

In main function, function InsertAtHead inserts value at the beginning of linked list. Inserting such values[for sake of simplicity] so that the list created is sorted.Examples :

Input : Enter value to search : 7 Output : Found Input : Enter value to search : 12 Output : Not Found

C++

// 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;

}

Java

// Java code to implement binary search

// on Singly Linked List

// Node Class

class Node

{

int data;

Node next;

// Constructor to create a new node

Node[int d]

{

data = d;

next = null;

}

}

class BinarySearch

{

// function to insert a node at the beginning

// of the Singaly Linked List

static Node push[Node head, int data]

{

Node newNode = new Node[data];

newNode.next = head;

head = newNode;

return head;

}

// Function to find middle element

// using Fast and Slow pointers

static Node middleNode[Node start, Node last]

{

if [start == null]

return null;

Node slow = start;

Node fast = start.next;

while [fast != last]

{

fast = fast.next;

if [fast != last]

{

slow = slow.next;

fast = fast.next;

}

}

return slow;

}

// function to insert a node at the beginning

// of the Singly Linked List

static Node binarySearch[Node head, int value]

{

Node start = head;

Node last = null;

do

{

// Find Middle

Node mid = middleNode[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 less than mid

else if [mid.data > value]

{

start = mid.next;

}

// If the value is more than mid.

else

last = mid;

} while [last == null || last != start];

// value not present

return null;

}

// Driver Code

public static void main[String[] args]

{

Node head = null;

// Using push[] function to

// convert singly linked list

// 10 -> 9 -> 8 -> 7 -> 4 -> 1

head = push[head, 1];

head = push[head, 4];

head = push[head, 7];

head = push[head, 8];

head = push[head, 9];

head = push[head, 10];

int value = 7;

if [binarySearch[head, value] == null]

{

System.out.println["Value not present"];

}

else

{

System.out.println["Present"];

}

}

}

// This code is contributed by Vivekkumar Singh

Python

# Python code to implement binary search

# on Singly Linked List

# Link list node

class Node:

def __init__[self, data]:

self.data = data

self.next = None

self.prev = None

def newNode[x]:

temp = Node[0]

temp.data = x

temp.next = None

return temp

# function to find out middle element

def middle[start, last]:

if [start == None]:

return None

slow = start

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

def binarySearch[head,value]:

start = head

last = None

while True :

# Find middle

mid = middle[start, last]

# If middle is empty

if [mid == None]:

return None

# If value is present at middle

if [mid . data == value]:

return mid

# If value is more than mid

elif [mid . data < value]:

start = mid . next

# If the value is less than mid.

else:

last = mid

if not [last == None or last != start]:

break

# value not present

return None

# Driver Code

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]

value = 7

if [binarySearch[head, value] == None]:

print["Value not present\n"]

else:

print["Present"]

# This code is contributed by Arnab Kundu

C#

// C# code to implement binary search

// on Singly Linked List

using System;

// Node Class

public class Node

{

public int data;

public Node next;

// Constructor to create a new node

public Node[int d]

{

data = d;

next = null;

}

}

class BinarySearch

{

// function to insert a node at the beginning

// of the Singaly Linked List

static Node push[Node head, int data]

{

Node newNode = new Node[data];

newNode.next = head;

head = newNode;

return head;

}

// Function to find middle element

// using Fast and Slow pointers

static Node middleNode[Node start, Node last]

{

if [start == null]

return null;

Node slow = start;

Node fast = start.next;

while [fast != last]

{

fast = fast.next;

if [fast != last]

{

slow = slow.next;

fast = fast.next;

}

}

return slow;

}

// function to insert a node at the beginning

// of the Singly Linked List

static Node binarySearch[Node head, int value]

{

Node start = head;

Node last = null;

do

{

// Find Middle

Node mid = middleNode[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 less than mid

else if [mid.data > value]

{

start = mid.next;

}

// If the value is more than mid.

else

last = mid;

} while [last == null || last != start];

// value not present

return null;

}

// Driver Code

public static void Main[String []args]

{

Node head = null;

// Using push[] function to

// convert singly linked list

// 10 -> 9 -> 8 -> 7 -> 4 -> 1

head = push[head, 1];

head = push[head, 4];

head = push[head, 7];

head = push[head, 8];

head = push[head, 9];

head = push[head, 10];

int value = 7;

if [binarySearch[head, value] == null]

{

Console.WriteLine["Value not present"];

}

else

{

Console.WriteLine["Present"];

}

}

}

// This code is contributed by Arnab Kundu

Javascript

<script>

// JavaScript code to implement binary search

// on Singly Linked List

// Node Class

class Node

{

constructor[data]

{

this.data = data;

this.next = null;

}

}

// function to insert a node at the beginning

// of the Singaly Linked List

function push[head, data]

{

var newNode = new Node[data];

newNode.next = head;

head = newNode;

return head;

}

// Function to find middle element

// using Fast and Slow pointers

function middleNode[start, last]

{

if [start == null]

return null;

var slow = start;

var fast = start.next;

while [fast != last]

{

fast = fast.next;

if [fast != last]

{

slow = slow.next;

fast = fast.next;

}

}

return slow;

}

// function to insert a node at the beginning

// of the Singly Linked List

function binarySearch[head, value]

{

var start = head;

var last = null;

do

{

// Find Middle

var mid = middleNode[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 less than mid

else if [mid.data > value]

{

start = mid.next;

}

// If the value is more than mid.

else

last = mid;

} while [last == null || last != start];

// value not present

return null;

}

// Driver Code

var head = null;

// Using push[] function to

// convert singly linked list

// 10 -> 9 -> 8 -> 7 -> 4 -> 1

head = push[head, 1];

head = push[head, 4];

head = push[head, 7];

head = push[head, 8];

head = push[head, 9];

head = push[head, 10];

var value = 7;

if [binarySearch[head, value] == null]

{

document.write["Value not present"];

}

else

{

document.write["Present"];

}

</script>

Output: Present

Time Complexity: O[N]
Auxiliary Space: O[1]


Article Tags :

Divide and Conquer

Linked List

Searching

Binary Search

Practice Tags :

Linked List

Searching

Divide and Conquer

Binary Search

Read Full Article

We just need traverse the list in order to search for a specific element in the list. Perform following operations in order to search a specific operation.

  • Copy head pointer into a temporary pointer variable ptr.
  • declare a local variable I and assign it to 0.
  • Traverse the list until the pointer ptr becomes null. Keep shifting pointer to its next and increasing i by +1.
  • Compare each element of the list with the item which is to be searched.
  • If the item matched with any node value then the location of that value I will be returned from the function else NULL is returned.

Binary Trees are a type of data structure where each data is stored as a node, and each node has two child nodes. The three primary traversal techniques are pre-order, in-order, and post-order.

Linked Lists are another type of data structure where data is stored in nodes, and each node is connected via links. A linked list can be singly linked or doubly-linked depending upon the number of links. The two pointers in a doubly-linked list are: next and previous.

In this article, we will learn to convert a given binary tree into a doubly-linked list by performing in-order traversal. To know more about the various tree traversals, click hereTree Traversals.