码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Add Two Numbers

时间:2014-10-27 22:58:01      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   使用   for   sp   

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) {
        if (l1 == NULL || l2 == NULL) {
            return l1 == NULL ? l1 : l2;
        }
        
        int carry = 0;
        ListNode *head = NULL;
        ListNode **prev = &head;
        
        while (l1 != NULL || l2  != NULL) {
            int sum = carry;
            
            int l1_val = 0;
            if(l1 != NULL) {
                l1_val = l1->val;
                l1 = l1->next;
            }
            
            int l2_val = 0;
            if (l2 != NULL) {
                l2_val = l2->val;
                l2 = l2->next;
            }
            
            sum += l1_val + l2_val;
            ListNode *pt = new ListNode(sum % 10);
            *prev = pt;
            prev = &(pt->next);
            carry = sum / 10;
        }
        
        if (carry) {
            ListNode *pt = new ListNode(carry);
            *prev = pt;
        }
        
        return head;
    }
};

 

《LeetCode 题解 (C++版)》(戴方勤 著 )中一种非常简洁的写法:

 1 class Solution {
 2 public:
 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
 4     ListNode head(-1); // 头节点
 5     int carry = 0;
 6     ListNode *prev = &head;
 7     for (ListNode *pa = l1, *pb = l2;
 8     pa != nullptr || pb != nullptr;
 9     pa = pa == nullptr ? nullptr : pa->next,
10     pb = pb == nullptr ? nullptr : pb->next,
11     prev = prev->next) {
12         const int ai = pa == nullptr ? 0 : pa->val;
13         const int bi = pb == nullptr ? 0 : pb->val;
14         const int value = (ai + bi + carry) % 10;
15         carry = (ai + bi + carry) / 10;
16         prev->next = new ListNode(value); // 尾插法
17     }
18     if (carry > 0)
19     prev->next = new ListNode(carry);
20 
21     return head.next;
22     }
23 };

 

  

[LeetCode] Add Two Numbers

标签:des   style   blog   io   color   ar   使用   for   sp   

原文地址:http://www.cnblogs.com/vincently/p/4055340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!