題目描述:
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
題目解析:
題目意思是,兩個鏈表相當於一個逆置的數字,將兩個鏈表的相應位置進行相加,最終結果存到一個鏈表中。注意要有進位。
比如題目中的兩個鏈表:342 + 465 = 807
思路:創建一個新的鏈表,指向最終結果的鏈表。當兩個鏈表不爲空時,兩個鏈表同時從頭開始遍歷,用一個變量temp記錄遍歷到的節點的和,每遍歷一個節點,更新一下temp,temp/10,如果有進位,temp就爲進位的值,如果沒有進位,temp就爲0.
AC代碼:
/**
* 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) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* head = new ListNode(0);
ListNode* cur = head;
int temp = 0;
while(l1 != NULL || l2 != NULL || temp != 0)
{
if(l1 != NULL)
{
temp += l1->val;
l1 = l1->next;
}
if(l2 != NULL)
{
temp += l2->val;
l2 = l2->next;
}
cur->next = new ListNode(temp % 10);
cur = cur->next;
temp = temp / 10;
}
return head->next;
}
};
(*^▽^*)