-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinked_list_sreaching.cpp
80 lines (67 loc) · 1.93 KB
/
Linked_list_sreaching.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
using namespace std;
// Define the structure of a Node
struct Node {
int data;
Node* next;
};
// Function to insert a node at the end of the list (helper function to create the list)
void insertAtEnd(Node** head, int newData) {
Node* newNode = new Node();
newNode->data = newData;
newNode->next = nullptr;
if (*head == nullptr) {
*head = newNode;
return;
}
Node* temp = *head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to search for an element in the linked list
bool searchElement(Node* head, int target) {
Node* current = head; // Start from the head of the list
while (current != nullptr) {
if (current->data == target) {
return true; // Element found
}
current = current->next; // Move to the next node
}
return false; // Element not found in the list
}
// Function to print the linked list
void printList(Node* head) {
while (head != nullptr) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main() {
Node* head = nullptr;
// Insert some nodes into the linked list
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
// Print the linked list
cout << "Linked List: ";
printList(head);
// Search for an element in the list
int target = 20;
if (searchElement(head, target)) {
cout << "Element " << target << " found in the list." << endl;
} else {
cout << "Element " << target << " not found in the list." << endl;
}
// Search for an element not in the list
target = 50;
if (searchElement(head, target)) {
cout << "Element " << target << " found in the list." << endl;
} else {
cout << "Element " << target << " not found in the list." << endl;
}
return 0;
}