Open Ayushsinhahaha opened 3 years ago
mind if i add some solved codes from leetcode..?
Add two numbers represented by linked lists.
// driver
using namespace std;
/ Linked list Node / struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } };
struct Node* buildList(int size) { int val; cin>> val;
Node* head = new Node(val);
Node* tail = head;
for(int i=0; i<size-1; i++)
{
cin>> val;
tail->next = new Node(val);
tail = tail->next;
}
return head;
}
void printList(Node* n) { while(n) { cout<< n->data << " "; n = n->next; } cout<< endl; }
// } Driver Code Ends /* node for linked list:
struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } };
/ struct Node rev(struct Node head) { struct Node curr,next,prev; prev=NULL; curr=head;
while(curr!= NULL){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
head=prev;
return head;
}
class Solution { public: //Function to add two numbers represented by linked list. struct Node addTwoLists(struct Node first, struct Node second) { // code here struct Node temp1=rev(first); struct Node temp2=rev(second); struct Node temp=NULL; struct Node *head=NULL;
int x=0,sum=0;
while(temp1 !=NULL || temp2!=NULL){
sum=x+(temp1?temp1->data:0) + (temp2?temp2->data:0);
x=(sum>=10)?1:0;
sum=sum%10;
if(head==NULL)
{ head=new Node(sum);
temp=head;}
else
{ temp->next=new Node(sum);
temp= temp->next;}
if(temp1)
temp1=temp1->next;
if(temp2)
temp2=temp2->next;}
if(x>0)
temp->next= new Node(x);
head=rev(head);
return head;
}
};
// { Driver Code Starts.
int main() { int t; cin>>t; while(t--) { int n, m;
cin>>n;
Node* first = buildList(n);
cin>>m;
Node* second = buildList(m);
Solution ob;
Node* res = ob.addTwoLists(first,second);
printList(res);
}
return 0;
} // } Driver Code Ends
Add the algorithms you implemented yourself