Now let's implement a method to search for an element in a linked list. We'll traverse through the linked list and compare the data value of each node with the target value we want to search. If we find a match, we'll return true
, indicating that the element is present in the linked list. If we reach the end of the list without finding a match, we'll return false
to indicate that the element is not present.
Here's the C++ code for implementing the search operation:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Linked List Node
5class Node {
6public:
7 int data;
8 Node* next;
9
10 Node(int value) {
11 data = value;
12 next = nullptr;
13 }
14};
15
16// Linked List Class
17class LinkedList {
18public:
19 Node* head;
20
21 LinkedList() {
22 head = nullptr;
23 }
24
25 // Insertion at the Beginning of the Linked List
26 void insert(int value) {
27 Node* newNode = new Node(value);
28 newNode->next = head;
29 head = newNode;
30 }
31
32 // Search for an Element in the Linked List
33 bool search(int value) {
34 Node* current = head;
35 while (current != nullptr) {
36 if (current->data == value) {
37 return true;
38 }
39 current = current->next;
40 }
41 return false;
42 }
43};
44
45int main() {
46 // Create a Linked List
47 LinkedList list;
48 list.insert(3);
49 list.insert(2);
50 list.insert(1);
51
52 // Search for an Element
53 int searchValue = 2;
54 bool isFound = list.search(searchValue);
55 if (isFound) {
56 cout << "Element " << searchValue << " is present in the Linked List." << endl;
57 } else {
58 cout << "Element " << searchValue << " is not present in the Linked List." << endl;
59 }
60
61 return 0;
62}
xxxxxxxxxx
62
}
using namespace std;
// Linked List Node
class Node {
public:
int data;
Node* next;
Node(int value) {
data = value;
next = nullptr;
}
};
// Linked List Class
class LinkedList {
public:
Node* head;
LinkedList() {
head = nullptr;
}
// Insertion at the Beginning of the Linked List
void insert(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment