Skip to content

Commit 33fa107

Browse files
Comparing if two singly linked list are the same solved
1 parent c61a5fb commit 33fa107

3 files changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"name":"Same to Same","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/same-to-same-1","interactive":false,"memoryLimit":512,"timeLimit":4000,"tests":[{"input":"10 20 30 40 -1\n10 20 30 40 -1\n","output":"YES\n","id":1720893617212},{"input":"10 20 30 40 -1\n10 20 30 -1\n","output":"NO\n","id":1720893617207},{"id":1720893617156,"input":"10 20 30 40 -1\n40 30 20 10 -1\n","output":"NO\n"}],"testType":"single","input":{"type":"stdin"},"output":{"type":"stdout"},"languages":{"java":{"mainClass":"Main","taskClass":"SameToSame"}},"batch":{"id":"d254daed-c58a-487e-88bf-cd9b36f8d677","size":1},"srcPath":"f:\\Tutorials\\Video Tutorials\\Phitron\\3. Basic Data Structures\\Same_to_Same.cpp"}

Same_to_Same.bin

52.1 KB
Binary file not shown.

Same_to_Same.cpp

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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 compare_and_show_output(Node *n1, Node *n2)
30+
{
31+
Node *Node1 = n1;
32+
Node *Node2 = n2;
33+
while (Node1 != NULL && Node2 != NULL)
34+
{
35+
if (Node1->val != Node2->val)
36+
{
37+
cout << "NO" << endl;
38+
return;
39+
}
40+
Node1 = Node1->next;
41+
Node2 = Node2->next;
42+
}
43+
44+
if (Node1 == NULL && Node2 == NULL)
45+
cout << "YES" << endl;
46+
else
47+
cout << "NO" << endl;
48+
}
49+
50+
int main()
51+
{
52+
Node *N1 = NULL;
53+
Node *N1Tail = NULL;
54+
Node *N2 = NULL;
55+
Node *N2Tail = NULL;
56+
57+
while (true)
58+
{
59+
long int val;
60+
cin >> val;
61+
if (val == -1)
62+
break;
63+
insert_at_tail(N1, N1Tail, val);
64+
}
65+
while (true)
66+
{
67+
long int val;
68+
cin >> val;
69+
if (val == -1)
70+
break;
71+
insert_at_tail(N2, N2Tail, val);
72+
}
73+
74+
compare_and_show_output(N1, N2);
75+
76+
return 0;
77+
}

0 commit comments

Comments
 (0)