1. 程式人生 > >leetcode鏈表--14、add-two-numbers(兩鏈表相加 得到新鏈表)

leetcode鏈表--14、add-two-numbers(兩鏈表相加 得到新鏈表)

logs 錯誤 align 描述 eight val str nodes sent

題目描述 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 /**
 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 int flag = 0;//進位 13 ListNode* tail = new ListNode(0); 14 ListNode* ptr = tail; 15 16 while(l1 != NULL || l2 != NULL) 17 { 18 int val1 = 0; 19 if(l1 != NULL) 20 { 21 val1 = l1->val; 22 l1 = l1->next;
23 } 24 25 int val2 = 0; 26 if(l2 != NULL) 27 { 28 val2 = l2->val; 29 l2 = l2->next; 30 } 31 32 int tmp = val1 + val2 + flag; 33 ptr->next = new ListNode(tmp % 10); 34 flag = tmp / 10; 35 ptr = ptr->next; 36 } 37 //處理結束了flag還有一個進位則新申請一個為1的結點連入鏈表 38 if(flag == 1) 39 { 40 ptr->next = new ListNode(1); 41 } 42 return tail->next; 43 } 44 };

leetcode鏈表--14、add-two-numbers(兩鏈表相加 得到新鏈表)