Skip to content

Commit e14bf3f

Browse files
authored
Merge pull request #504 from harshal-169/main
Compare two linked lists.cpp
2 parents 2225518 + e9418a5 commit e14bf3f

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
// Linked list Node structure
4+
struct Node
5+
{
6+
char c;
7+
struct Node *next;
8+
9+
Node(char x){
10+
c = x;
11+
next = NULL;
12+
}
13+
14+
};
15+
16+
17+
int compare(Node *list1, Node *list2);
18+
19+
20+
int main()
21+
{
22+
int t,n;
23+
cin>>t;
24+
char x;
25+
while(t--)
26+
{
27+
cin>>n;
28+
cin>>x;
29+
Node *list1 = new Node(x);
30+
Node *temp=list1;
31+
for(int i=0;i<n-1;i++){
32+
cin>>x;
33+
temp->next = new Node(x);
34+
temp=temp->next;
35+
}
36+
int m;
37+
cin>>m;
38+
cin>>x;
39+
Node *list2 = new Node(x);
40+
temp=list2;
41+
for(int i=0;i<m-1;i++){
42+
cin>>x;
43+
temp->next = new Node(x);
44+
temp=temp->next;
45+
}
46+
47+
cout << compare(list1, list2)<<endl;
48+
}
49+
return 0;
50+
}
51+
// } Driver Code Ends
52+
53+
54+
/* Linked list Node structure
55+
struct Node
56+
{
57+
char c;
58+
struct Node *next;
59+
60+
Node(char x){
61+
c = x;
62+
next = NULL;
63+
}
64+
65+
};
66+
*/
67+
68+
// Compare two strings represented as linked lists
69+
int compare(Node *list1, Node *list2)
70+
{
71+
// Code Here
72+
Node *cur1=list1,*cur2=list2;
73+
while(cur1!=NULL && cur2!=NULL)
74+
{
75+
if(cur1->c > cur2->c)
76+
return 1;
77+
if(cur1->c < cur2->c)
78+
return -1;
79+
80+
81+
cur1=cur1->next;
82+
cur2=cur2->next;
83+
}
84+
85+
if(cur1!=NULL)
86+
return 1;
87+
if(cur2!=NULL)
88+
return -1;
89+
return 0;
90+
}

0 commit comments

Comments
 (0)