forked from ambujraj/hacktoberfest2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.cc
66 lines (60 loc) · 1.26 KB
/
search.cc
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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int d){
data = d;
next = NULL;
}
};
Node* insertAtEnd(Node* head, int x, Node* &tail){
if (head == NULL){
head = new Node(x);
tail = head;
return head;
}
tail->next = new Node(x);
tail = tail->next;
return head;
}
Node* createLL(){
int x;
Node* head = NULL;
Node* tail = NULL;
while(true){
cin >> x;
if (x == -1) break;
head = insertAtEnd(head, x, tail);
}
return head;
}
int searchLL(Node* head,int data){
Node* cur = head;
int count=0;
while(cur != NULL){
count++;
if(cur->data==data){
return count;
}
cur=cur->next;
}
return -1;
}
int main(){
//enter -1 for last number
Node* head=createLL();
//To search an element in link list use searchLL if not present it will return -1
// otherwise it will return index of element in linked list
int data;
cout<<"enter the element data to be searched"<<endl;
cin >> data;
int index=searchLL(head,data);
if (index==-1){
cout<<"element not found"<<endl;
}
else{
cout<<"element is present"<<endl;
}
}