标签:
题目:
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
解题思路:
从头至尾遍历两个链表,注意进位。
/** * 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* temp1 = l1; ListNode* temp2 = l2; ListNode* head = NULL; ListNode* tail = NULL; int carry = 0; while(temp1 != NULL || temp2 != NULL) { int val1 = (temp1 != NULL)?temp1->val:0; int val2 = (temp2 != NULL)?temp2->val:0; int sum = (val1+val2+carry)%10; carry = (val1+val2+carry)/10; if(head == NULL) { head = new ListNode(sum); tail = head; } else { tail->next = new ListNode(sum); tail = tail->next; } temp1 = (temp1 != NULL)?temp1->next:NULL; temp2 = (temp2 != NULL)?temp2->next:NULL; } if(carry > 0) { tail->next = new ListNode(carry); tail = tail->next; } return head; } };
[LeetCode In C++] 2. Add Two Numbers
标签:
原文地址:http://www.cnblogs.com/wwwjjjfff/p/4851699.html