2.两数相加

mac2026-01-18  7

Leetcode刷题笔记–两数相加

1.题目描述

2.解题方法

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *r = l1; ListNode *u = l1;//r,u指向链表l1 int c1 = 0, c2 = 0;//c2记录低位相加的结果,c1高位进位的值 while (l1 || l2) { if (l1) { c1 += l1->val; l1 = l1->next; } if (l2) { c1 += l2->val;//两个链表的值相加到c1上 l2 = l2->next; } c2 = c1%10;//取余操作 c2记录低位相加结果 c1 /= 10;//c1记录高位进位的值 u->val = c2;//将c2存入到新链表中 if (l1) { u->next = l1;//如果l1更长,则将剩余的l1加入到u中 u = u->next; } else if (l2) { u->next = l2;//如果l2更长,则将剩余的l2加入到u中 u = u->next; } } if (c1) { //如果两个链等长且最后有进位,进位的c1加入链表中 ListNode *x = new ListNode(c1); u->next = x; } return r; } };
最新回复(0)