Skip to content

Compare two linked lists.cpp #504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions Linked List Basics/Compare two linked lists.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#include<bits/stdc++.h>
using namespace std;
// Linked list Node structure
struct Node
{
char c;
struct Node *next;

Node(char x){
c = x;
next = NULL;
}

};


int compare(Node *list1, Node *list2);


int main()
{
int t,n;
cin>>t;
char x;
while(t--)
{
cin>>n;
cin>>x;
Node *list1 = new Node(x);
Node *temp=list1;
for(int i=0;i<n-1;i++){
cin>>x;
temp->next = new Node(x);
temp=temp->next;
}
int m;
cin>>m;
cin>>x;
Node *list2 = new Node(x);
temp=list2;
for(int i=0;i<m-1;i++){
cin>>x;
temp->next = new Node(x);
temp=temp->next;
}

cout << compare(list1, list2)<<endl;
}
return 0;
}
// } Driver Code Ends


/* Linked list Node structure
struct Node
{
char c;
struct Node *next;

Node(char x){
c = x;
next = NULL;
}

};
*/

// Compare two strings represented as linked lists
int compare(Node *list1, Node *list2)
{
// Code Here
Node *cur1=list1,*cur2=list2;
while(cur1!=NULL && cur2!=NULL)
{
if(cur1->c > cur2->c)
return 1;
if(cur1->c < cur2->c)
return -1;


cur1=cur1->next;
cur2=cur2->next;
}

if(cur1!=NULL)
return 1;
if(cur2!=NULL)
return -1;
return 0;
}