Add two numbers of two linked list(each digit in one node)


   

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution 
{
public:
    ListNode* addTwoNumbers(ListNode* l1ListNode* l2
    {
        ListNode*temp1, *temp2, *head=0, *temp, *newnode;
        temp1=l1;
        temp2=l2;
        int x,y=0;
        while(temp1!=0 && temp2!=0)
        {
            x=temp1->val + temp2->val + y;
            y=x/10;
            
            newnode=new ListNode(x%10);
            if(head==0)
            {head=newnode; temp=newnode;}
            else 
            {temp->next=newnode; temp=newnode;}
            
            
            temp1=temp1->next;
            temp2=temp2->next;
        }
        while(temp1!=0)
        {
            x=temp1->val + y;
            y=x/10;
            newnode=new ListNode(x%10);
            if(head==0)
            {head=newnode; temp=newnode;}
            else 
            {temp->next=newnode; temp=newnode;}
            temp1=temp1->next;
        }
        while(temp2!=0)
        {
            x=temp2->val + y;
            y=x/10;
            newnode=new ListNode(x%10);
            if(head==0)
            {head=newnode; temp=newnode;}
            else 
            {temp->next=newnode; temp=newnode;}
            temp2=temp2->next;
        }
        while(y!=0)
        {
            x=y%10;
            y=y/10;
            newnode=new ListNode(x%10);
            if(head==0)
            {head=newnode; temp=newnode;}
            else 
            {temp->next=newnode; temp=newnode;}
        }
        return head;
    }
};

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree