Mark As Completed Discussion

To search for a specific value in a linked list, you can traverse the list and compare each node's data with the target value. Here's an example of how to search for a value in a singly linked list using C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class Node {
5public:
6    int data;
7    Node* next;
8
9    Node(int data) {
10        this->data = data;
11        next = nullptr;
12    }
13};
14
15// Function to search for a value in a linked list
16bool searchLinkedList(Node* head, int value) {
17    Node* current = head;
18    while (current != nullptr) {
19        if (current->data == value) {
20            return true;
21        }
22        current = current->next;
23    }
24    return false;
25}
26
27int main() {
28    // Create the head of the list
29    Node* head = new Node(1);
30
31    // Add nodes to the list
32    Node* node1 = new Node(2);
33    head->next = node1;
34    Node* node2 = new Node(3);
35    node1->next = node2;
36    Node* node3 = new Node(4);
37    node2->next = node3;
38    Node* node4 = new Node(5);
39    node3->next = node4;
40
41    // Search for a value in the list
42    int value = 3;
43    bool found = searchLinkedList(head, value);
44    if (found) {
45        cout << "Value " << value << " found in the linked list" << endl;
46    } else {
47        cout << "Value " << value << " not found in the linked list" << endl;
48    }
49
50    return 0;
51}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment