LeetCode.2

  You are given two non-empty linked lists representing two non-negative integers. 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.

  You may assume the two numbers do not contain any leading zero, except the number 0 itself.

  Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 0 -> 8

  题意大致是说将两组用链表保存的数据单独相加,低一位上的和大于10,则进位到高一位上,并将数据用链表保存,比如:123和987两组数是用链表保存的:1 -> 2 -> 3,9 -> 8-> 7,1 + 9 = 10,则该位为0,向下一位中进1,下一位中2 + 8 = 10,加1后得到11,向下一位中进1,该位为1,下一位中3 + 7 = 10,加1得到11,该位为1,多一个1需要再加一个链表来保存它,结果:0 -> 1 -> 1 -> 1- > 1。

  下面是解决方案(C语言):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode * addTwoNumbers(struct ListNode * l1, struct ListNode * l2) {
    struct ListNode * sum;
    struct ListNode * t;
    struct ListNode * s, * AddNode;
    int num1, num2;
    int flag = 0;

    if (l1 == NULL) return l2;
    if (l2 == NULL) return l1;
    
    sum = (struct ListNode *)malloc(sizeof(struct ListNode));
    s = sum;
    while(l1 || l2)
    {
        t = (struct ListNode *)malloc(sizeof(struct ListNode));
        num1 = l1 == NULL? 0 : l1 -> val;
        num2 = l2 == NULL? 0 : l2 -> val;
        t -> val = num1 + num2 + flag;
        flag = (t -> val > 9) ? 1 : 0;
        if(flag)
            t -> val %= 10;
        if(l1 != NULL)
            l1 = l1 -> next;
        if(l2 != NULL)
            l2 = l2 -> next;
        s -> next = t;
        s = t;
        t -> next = NULL;        //一开始提交很多次都不过,错误竟然是没有写这个
    }
    if(flag)
    {
        AddNode = (struct ListNode *)malloc(sizeof(struct ListNode));
        AddNode -> val = flag;
        AddNode -> next = NULL;
        t -> next = AddNode;
    }
    
    return sum -> next;
}

  Submission Result: Accepted.

原文地址:https://www.cnblogs.com/darkchii/p/7568099.html