Implement searching of a node algorithm in singly linked list in C++
Code
#include <iostream>using namespace std;class Node {public:int data;Node *next;};bool searchNode(Node *head, int key) {Node *current = head;while (current != NULL) {if (current->data == key) {return true;}current = current->next;}return false;}int main() {Node *head = NULL;Node *second = NULL;Node *third = NULL;head = new Node();second = new Node();third = new Node();head->data = 1;head->next = second;second->data = 2;second->next = third;third->data = 3;third->next = NULL;if (searchNode(head, 2)) {cout << "Node found" << endl;} else {cout << "Node not found" << endl;}return 0;}
Output
run the code
0 Comments
Post a Comment