In: Computer Science
Write a c++ member function that sequentially searches for a specific element in a doubly linked list. return the position if found or -1 is the element cannot be found.
Write a c++ member function that sequentially searches for a specific element in a doubly linked list. return the position if found or -1 is the element cannot be found.
Code :-
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
void insertNode(struct Node** start, int value)
{
if (*start == NULL)
{
struct Node* new_node = new Node;
new_node->data = value;
new_node->next = new_node->prev = new_node;
*start = new_node;
return;
}
Node *last = (*start)->prev;
struct Node* new_node = new Node;
new_node->data = value;
new_node->next = *start;
(*start)->prev = new_node;
new_node->prev = last;
last->next = new_node;
}
void displayList(struct Node* start)
{
struct Node *temp = start;
while (temp->next != start)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("%d ", temp->data);
}
int searchList(struct Node* start, int search)
{
struct Node *temp = start;
int count=0,flag=0,value;
if(temp == NULL)
return -1;
else
{
while(temp->next != start)
{
count++;
if(temp->data == search)
{
flag = 1;
count--;
break;
}
temp = temp->next;
}
if(temp->data == search)
{
count++;
flag = 1;
}
// If flag is true, then element found
// else the element cannot be found so return -1
if(flag == 1)
cout<<"\n"<<search <<"\nfound at location "<<count<<endl;
else
cout<<"\n"<<search <<"\n-1"<<endl;
}
}
int main()
{
/* Start with the empty list */
struct Node* start = NULL;
// Insert 17. So linked list becomes 17->NULL
insertNode(&start, 17);
// Insert 25. So linked list becomes 17->25
insertNode(&start, 25);
// Insert 9. So linked list
// becomes 17->25->9
insertNode(&start, 9);
// Insert 8. So linked list
// becomes 17->25->9->18
insertNode(&start, 18);
// Insert 6. So linked list
// becomes 17->25->9->18->6
insertNode(&start, 6);
printf("Created doubly linked list is: ");
displayList(start);
printf("\nEnter the element you want to search: ");
searchList(start, 9);
return 0;
}
Screenshot of code and output :-
Code :-
Output :-