diff --git a/Linked List Basics/Compare two linked lists.cpp b/Linked List Basics/Compare two linked lists.cpp new file mode 100644 index 00000000..ec331af5 --- /dev/null +++ b/Linked List Basics/Compare two linked lists.cpp @@ -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; +}