mercredi 26 août 2020

Why I am not able to print first element in this Linked List?

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            
            vector<int> a1;
            vector<int> a2;
            vector<int> result;
            while(l1->next||l2->next)
            {
                a1.push_back(l1->val);
                a2.push_back(l2->val);
                l1=l1->next;
                l2=l2->next;
            }
            int v1=0;
            int v2=0;
            for(auto d:a1)
            {
                v1=v1*10+d;
                
            }
            for(auto f:a2)
            {
                v2=v2*10+f;
            }
            int v3=v1+v2;
            int r;
            while(v3>0)
            {
                r=v3%10;
                v3=v3/10;
                result.push_back(r);
                
            }
            ListNode* p= new ListNode(result[0]);
            ListNode* start=p;
            ListNode* add=p;
            int i;
            for(i=1;i<result.size();i++)
            {
                ListNode* temp=new ListNode(result[i]);
                
                add->next=temp;
                add=add->next;
            }
            return p;
        }
    };

Output(1st element of the linked list is not printing)

Input: [2,4,3]
       [5,6,4]
               
Your answer:[0,8]              
Expected answer:[7,0,8]
       

I am not able to print the first element of the resultant linked list. I Tried with different test cases and its printing everything right except the first element.

Aucun commentaire:

Enregistrer un commentaire