167.リンクリストの合計

167.リンクリストの合計
 

リンクリストで表される2つの整数があり、各ノードには数値が含まれています。番号は元の整数の逆の順序で格納されるため、最初の番号はリンクリストの先頭にあります。2つの整数を加算し、その合計をリンクリストの形式で返す関数を記述します。
サンプル

例1:

入力:7-> 1-> 6-> null、5-> 9-> 2-> null
出力:2-> 1-> 9-> null    
サンプルの説明:617 + 295 = 912、912リンクリストに変換:2-> 1-> 9-> null

例2:

入力:3-> 1-> 5-> null、5-> 9-> 2-> null
出力:8-> 0-> 8-> null    
サンプルの説明:513 + 295 = 808、808リンクリストに変換:8-> 0-> 8-> null

 ListNode * addLists(ListNode * l1、ListNode * l2){         //ここにコードを記述します         std :: queue <int> q1;         while(l1)         {             q1.push(l1-> val);             l1 = l1-> next;         }         std :: queue <int> q2;         while(l2)         {             q2.push(l2-> val);             l2 = l2-> next;         }         std :: queue <int> q3;         int num = 0;         while(!q1.empty()&&!q2.empty())         {             int a = q1.front();             q1.pop();             int b = q2.front();             q2.pop();

        






        







         







            
            int c = a + b + num;
            int d = c%10;
            num = c / 10;
            q3.push(d);
        }
        
        while(!q1.empty())
        {             int a = q1.front();             q1.pop();             int c = a + num;             int d = c%10;             num = c / 10;             q3.push(d);         }         while(!q2.empty())         {             int b = q2.front();             q2.pop();             int c = b + num;             int d = c%10;             num = c / 10;             q3.push(d);         }


        





        




            





        
        if(num> 0)
        {             q3.push(num);         }         // std:cout << q3.size()<< std :: endl;         ListNode * head = nullptr;         if(!q3.empty())         {            head = new ListNode(q3.front());            q3.pop();         }         ListNode * p = head;         while(!q3.empty())         {            ListNode * node = new ListNode(q3.front());            q3.pop();            p-> next = node;            p = p-> next;         }         リターンヘッド;        }


        

        

       













        
       
      

        

おすすめ

転載: blog.csdn.net/yinhua405/article/details/111941010