Search Element in Linked List
In this article you will see how we can search element in linked list. We will see both iterative and recursive way of doing this.
Insertion in linked list :
123456789101112131415161718#include<iostream> using namespace std; class node { public: int data; node* next; }; void push(node** head_ref, int new_data) { node* new_node = new node(); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node; }
Other Resources : Data Structures, Algorithms, Competitive Coding, Development
Iterative Searching :
1234567891011121314151617void search(node** head_ref, int key) { int c = 0; node *temp = *head_ref; if(temp != NULL && temp->data == key) cout << "Found position : " << 0; else { while(temp != NULL && temp->data != key) { temp = temp->next; c++; } cout << "Found position iteratively : " << c; } }
Recursive Searching :
12345678910void search1(node* head_ref, int key, int c) { if(head_ref->data == key) { cout << "\nFound position recursively : " << c; return; } return search1(head_ref->next, key, c++); }
Other Resources : Data Structures, Algorithms, Competitive Coding, Development
Display :
123456789void show(node *Node) { while(Node != NULL) { cout << Node->data << " "; Node = Node->next; } }
Main :
12345678910111213141516171819int main() { node *head= NULL; int n1, n2, n3, n4, ele; cin >> n1 >> n2 >> n3 >> n4; push(&head, n1); push(&head, n2); push(&head, n3); push(&head, n4); show(head); cout << "Element to search : "; cin >> ele; search(&head, ele); int c = 0; search1(head, ele, c); return 0; }
No comments:
If you have any doubt or suggestion let me know in comment section.