【Leetcode】【Medium】Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
本题特点:
1、链表已经是倒序的,因此首结点就是个位数字;
解题步骤:
1、建立preHead结点,指向新链表表头,新链表记录加法结果;(注意新建链表,不要在原链表上操作)
2、新建整形flag,记录进位;
3、开始循环操作,只要L1和L2有一个不为空,循环继续:
(1)新建临时整形sum,初始值为flag;
(2)L1不为空,则加上L1的值;L2不为空,则加上L2的值;
(3)flag = sum / 10; sum = sum % 10;
(4)记录在新建链表上;
4、如果flag还存在值,则再新建一个结点;
5、记录preHead->next地址head,delete preHead,返回head;
代码:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 ListNode* preheader = new ListNode(0); 13 ListNode* newlist = preheader; 14 int flag = 0; 15 16 while (l1 || l2) { 17 int sum = flag; 18 if (l1) { 19 sum += l1->val; 20 l1 = l1->next; 21 } 22 if (l2) { 23 sum += l2->val; 24 l2 = l2->next; 25 } 26 27 flag = sum / 10; 28 sum = sum % 10; 29 newlist->next = new ListNode(sum); 30 newlist = newlist->next; 31 } 32 33 if (flag) 34 newlist->next = new ListNode(flag); 35 36 return preheader->next; 37 } 38 };