Search an element in a Doubly Linked List | C ++ program to implement the above approach ; Structure of a node of the doubly linked list ; Stores data value of a node ; Stores pointer to next node ; Stores pointer to previous node ; Function to insert a node at the beginning of the Doubly Linked List ; Allocate memory for new node ; Insert the data ; Since node is added at the beginning , prev is always NULL ; Link the old list to the new node ; If pointer to head is not NULL ; Change the prev of head node to new node ; Move the head to point to the new node ; Function to find the position of an integer in doubly linked list ; Stores head Node ; Stores position of the integer in the doubly linked list ; Traverse the doubly linked list ; Update pos ; Update temp ; If the integer not present in the doubly linked list ; If the integer present in the doubly linked list ; Driver Code ; Create the doubly linked list 18 < -> 15 < -> 8 < -> 9 < -> 14
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; Node * prev ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = ( Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> prev = NULL ; new_node -> next = ( * head_ref ) ; if ( ( * head_ref ) != NULL ) { ( * head_ref ) -> prev = new_node ; } ( * head_ref ) = new_node ; } int search ( Node * * head_ref , int x ) { Node * temp = * head_ref ; int pos = 0 ; while ( temp -> data != x && temp -> next != NULL ) { pos ++ ; temp = temp -> next ; } if ( temp -> data != x ) return -1 ; return ( pos + 1 ) ; } int main ( ) { Node * head = NULL ; int X = 8 ; push ( & head , 14 ) ; push ( & head , 9 ) ; push ( & head , 8 ) ; push ( & head , 15 ) ; push ( & head , 18 ) ; cout << search ( & head , X ) ; return 0 ; }