首页 > 其他分享 >2. 两数相加

2. 两数相加

时间:2023-02-18 23:00:55浏览次数:35  
标签:ListNode val sum next currentNodeOfl2 currentNodeOfNewList 相加

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

题解:

很常规的链表遍历解法

/**
 * 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* l1, ListNode* l2) {
        ListNode * currentNodeOfL1, * currentNodeOfl2;
          currentNodeOfL1 = l1; 
          currentNodeOfl2 = l2;
          ListNode * newListHead, * currentNodeOfNewList;
          newListHead = currentNodeOfNewList = new ListNode();
          int addnext = 0;
          int sum = 0;
          for(; currentNodeOfL1 != nullptr && currentNodeOfl2 != nullptr; currentNodeOfL1 = currentNodeOfL1->next, currentNodeOfl2 = currentNodeOfl2->next) {
               sum = currentNodeOfL1->val + currentNodeOfl2->val + addnext;
               addnext = sum/10;
               sum = sum % 10;
               currentNodeOfNewList->val = sum; 
               currentNodeOfNewList->next = new ListNode();
               currentNodeOfNewList = currentNodeOfNewList->next;
          }

          for(; currentNodeOfL1 != nullptr; currentNodeOfL1 = currentNodeOfL1->next) {
               sum = currentNodeOfL1->val+ addnext;
               addnext = sum/10;
               sum = sum % 10;
               currentNodeOfNewList->val = sum; 
               currentNodeOfNewList->next = new ListNode();
               currentNodeOfNewList = currentNodeOfNewList->next;
          }

          for(; currentNodeOfl2 != nullptr; currentNodeOfl2 = currentNodeOfl2->next) {
               sum = currentNodeOfl2->val+ addnext;
               addnext = sum/10;
               sum = sum % 10;
               currentNodeOfNewList->val = sum; 
               currentNodeOfNewList->next = new ListNode();
               currentNodeOfNewList = currentNodeOfNewList->next;
          }

          if (addnext != 0) {
               currentNodeOfNewList->val = addnext;
          } else {
               ListNode * i = newListHead;
               for (; i->next != currentNodeOfNewList; i = i->next) {
                    
               }
               i->next = nullptr;
               delete currentNodeOfNewList;

          }
          
          return newListHead;
    }
};

  

标签:ListNode,val,sum,next,currentNodeOfl2,currentNodeOfNewList,相加
From: https://www.cnblogs.com/woodx/p/17133897.html

相关文章