算法-两数相加

217 阅读1分钟

/* 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807

*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n1 = l1;
    struct ListNode* n2 = l2;
    struct ListNode* n3 = l3;
    int carry = 0;
    while (1) {
        int c1 = 0;
        int c2 = 0;
        if (n1 != NULL) {
            c1 = n1->val;
            n1 = n1 ->next;
        }
        if (n2 != NULL) {
            c2 = n2->val;
            n2 = n2 ->next;
        }
        int sum = c1 + c2 + carry;
        carry = sum /10;
        int currentValue = sum % 10;
        n3->val = currentValue;
        //考虑进位有值得情况需要进入下一个循环
        if(n1 != NULL || n2 != NULL || carry)
        {
            struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
            n3->next = newNode;
            n3 = n3 ->next;
        }
        else
        {
        //最后一个节点为NULL
            n3 ->next = NULL;
            break;
        }
    }
   
    return l3;
}

小结:面向过程的思路。 注意的几个问题:

  1. 进位问题,低位相加得出进位值提供给高位计算。
  2. 最后一轮相加的时候可能会产生进位,这个时候需要进入下一轮循环,计算下一位的值。

待完善L('ω')┘三└('ω')」....