From e853a59540b9eb1ce040b9d45d5f4c5fa4b7d148 Mon Sep 17 00:00:00 2001 From: Aditya Chouksey Date: Fri, 24 Oct 2025 11:09:42 +0530 Subject: [PATCH] Create searchelemnet_in_linkedlist.cpp The program creates a singly linked list. Takes user input to add nodes. Searches the linked list node-by-node for the given key. Returns whether the element is found or not. --- .../searchelemnet_in_linkedlist.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 data_structures/linked_list/searchelemnet_in_linkedlist.cpp diff --git a/data_structures/linked_list/searchelemnet_in_linkedlist.cpp b/data_structures/linked_list/searchelemnet_in_linkedlist.cpp new file mode 100644 index 0000000000..79ad58b533 --- /dev/null +++ b/data_structures/linked_list/searchelemnet_in_linkedlist.cpp @@ -0,0 +1,75 @@ +#include +using namespace std; + +// Node structure +struct Node { + int data; + Node* next; +}; + +// Function to insert a new node at the end +void insert(Node*& head, int value) { + Node* newNode = new Node(); + newNode->data = value; + 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 search(Node* head, int key) { + Node* current = head; + while (current != nullptr) { + if (current->data == key) + return true; + current = current->next; + } + return false; +} + +// Function to display the linked list +void display(Node* head) { + Node* temp = head; + while (temp != nullptr) { + cout << temp->data << " -> "; + temp = temp->next; + } + cout << "NULL" << endl; +} + +// Main function +int main() { + Node* head = nullptr; + int n, value, key; + + cout << "Enter number of elements: "; + cin >> n; + + cout << "Enter elements:\n"; + for (int i = 0; i < n; i++) { + cin >> value; + insert(head, value); + } + + cout << "Linked List: "; + display(head); + + cout << "Enter element to search: "; + cin >> key; + + if (search(head, key)) + cout << "Element " << key << " found in the list." << endl; + else + cout << "Element " << key << " not found in the list." << endl; + + return 0; +}