[LeetCode]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

解题方案:

题目意思很简单,但是我调试了半天,并且提交了很多次,拉低了整体AC率。下面是该题代码:

 1 class Solution {
 2 public:
 3     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
 4         int carry = 0;
 5 
 6         struct ListNode *head1 = l1;
 7         struct ListNode *head2 = l2;
 8         struct ListNode *pre = NULL;
 9 
10         int count1 = 0;
11         int count2 = 0;
12         while (head1 != NULL) { ++count1; head1 = head1->next;}
13         while (head2 != NULL) { ++count2; head2 = head2->next;}
14         if (count1 < count2) {
15             struct ListNode *temp = l1;
16             l1 = l2;
17             l2 = temp;
18         }
19 
20         head1 = l1;
21         head2 = l2;
22 
23         while (true) {
24             int temp = head1->val + head2->val;
25             head1->val = (temp + carry) % 10;
26             carry = (temp + carry) / 10;
27 
28             pre   = head1;
29             head1 = head1->next;
30             head2 = head2->next;
31             if (head2 == NULL) {
32                 break;
33             }
34         }
35 
36         while(head1 != NULL) {
37             int temp = head1->val;
38             head1->val = (temp + carry) % 10;
39             carry = (temp + carry) / 10;
40             pre = head1;
41             head1 = head1->next;
42         }
43 
44         if (carry != 0) {
45             struct ListNode *last = new ListNode(carry);
46             pre->next = last;
47         }
48         return l1;
49     }
50 };
原文地址:https://www.cnblogs.com/skycore/p/4031216.html