(有部分参考)445. Add Two Numbers II - C语言

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Example:

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

题目要求:倒序将两链表的值相加,并加新链表倒序输出。

考察点:1.进位 2.两链表长短不一致的情况 3.链表的倒序 4.链表的建立

声明::关于2 & 4 ,有参考https://blog.csdn.net/godlovelong/article/details/70224437

My method

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode *node) {
    struct ListNode *p = node, *q = node->next, *t;
    while (p && q) {
        t = q->next;
        q->next = p;
        p = q;
        q = t;
    }
    node->next = NULL; //Do not forget! Or else p will loop

    return p;
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int last = 0; //进位
    struct ListNode *t1, *t2;
    struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode));
    ret->val = 0;
    struct ListNode *node = NULL;
    
    t1 = (l1->next == NULL) ? l1 : (reverseList(l1));
    t2 = (l2->next == NULL) ? l2 : (reverseList(l2));
    while (t1 || t2 || last) {//t1有node 或 t2有node 或 还有进位
        if (node == NULL) {
            node = ret;
        } else { //only malloc if the conditions are met
            node->next = (struct ListNode *)malloc(sizeof(struct ListNode));//逐个node进行malloc
            node->next->val = 0;
            node = node->next;
        }
        int a = t1 ? t1->val : 0;
        int b = t2 ? t2->val : 0;
        node->val = (a + b + last) % 10;
        last = (a + b + last) / 10;
        node->next = NULL; //need set NULL to node->next in case the conditions are not met.
        
        t1 = t1 ? (t1->next) : NULL;
        t2 = t2 ? (t2->next) : NULL;     
    }
    /*少考虑了还有进位的情况
    while (t1) {
        node->val = (t1->val + last) % 10;
        last = (t1->val + last) / 10;
        node->next = NULL;
        t1 = t1->next;
    }
    while (t2) {
        node->val = (t2->val + last) % 10;
        last = (t2->val + last) / 10;
        node = node->next;
        t2 = t2->next;
    }*/
    return reverseList(ret);
}

特别声明:

关于处理两链表长短不一的情况以及新node的建立,有参考: https://blog.csdn.net/godlovelong/article/details/70224437

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值