Skip to content

Commit c61a5fb

Browse files
Linked List Search Problem Solved, DSA, Assignment-2, problem-2
1 parent e064b9a commit c61a5fb

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"name":"Search","group":"HackerRank - Assignment 02 | Basic Data Structures | Batch 05","url":"https://www.hackerrank.com/contests/assignment-02-a-basic-data-structures-a-batch-05/challenges/search-12","interactive":false,"memoryLimit":512,"timeLimit":4000,"tests":[{"id":1720890201471,"input":"4\n1 2 3 4 5 -1\n3\n1 2 3 -1\n5\n1 -1\n1\n10 20 -1\n20\n","output":"2\n-1\n0\n1\n"}],"testType":"single","input":{"type":"stdin"},"output":{"type":"stdout"},"languages":{"java":{"mainClass":"Main","taskClass":"Search"}},"batch":{"id":"4b9a8426-94f1-4091-83da-70b503ca18c0","size":1},"srcPath":"f:\\Tutorials\\Video Tutorials\\Phitron\\3. Basic Data Structures\\Search.cpp"}

Search.bin

52.4 KB
Binary file not shown.

Search.cpp

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Node
5+
{
6+
public:
7+
long int val;
8+
Node *next;
9+
Node(int val)
10+
{
11+
this->val = val;
12+
this->next = NULL;
13+
}
14+
};
15+
16+
void insert_at_tail(Node *&head, Node *&tail, long int val)
17+
{
18+
Node *newNode = new Node(val);
19+
if (head == NULL)
20+
{
21+
head = newNode;
22+
tail = newNode;
23+
return;
24+
}
25+
tail->next = newNode;
26+
tail = newNode;
27+
}
28+
29+
void check_if_exist_and_show_output(Node *head, long int x)
30+
{
31+
Node *tmp = head;
32+
int i = 0;
33+
while (tmp != NULL)
34+
{
35+
if (tmp->val == x)
36+
{
37+
cout << i << endl;
38+
return;
39+
}
40+
else
41+
i++;
42+
tmp = tmp->next;
43+
}
44+
cout << "-1" << endl;
45+
}
46+
47+
int main()
48+
{
49+
50+
int t;
51+
cin >> t;
52+
while (t--)
53+
{
54+
Node *head = NULL;
55+
Node *tail = NULL;
56+
while (true)
57+
{
58+
long int val;
59+
cin >> val;
60+
if (val == -1)
61+
break;
62+
insert_at_tail(head, tail, val);
63+
}
64+
65+
long int x;
66+
cin >> x;
67+
check_if_exist_and_show_output(head, x);
68+
}
69+
70+
return 0;
71+
}

0 commit comments

Comments
 (0)