【链表】两个链表相加

步骤

1、 任意一个链表为空,返回另一个链表就行了,因为链表为空相当于0,0加任何数为0,包括另一个加数为0的情况。

2、反转两个待相加的链表,反转过程可以参考反转链表

3、设置返回链表的链表头,设置进位carry=0

4、从头开始遍历两个链表,直到两个链表节点都为空,carry也不为1.每次取出不为空的链表节点值,为空就设置为0,将两个数字与carry相加,然后查看是否进位,将进位后的结果(对10取模)加入新的链表节点,连接在返回链表后面,并继续往后遍历

5、返回前将结果链表再反转回来

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
#include <stdio.h>
#include <stdlib.h>
struct ListNode * reverseList(struct ListNode *head)
{
    if (head == NULL) {
        return NULL;
    }
    struct ListNode *cur = head;
    struct ListNode *pre = NULL;
    struct ListNode *temp = NULL;
    while (cur != NULL) {
        temp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
}


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    if(head1 == NULL)
    {
        return head2;
    }
    if(head2 == NULL)
    {
        return head1;
    }
    //反转链表
    head1 = reverseList(head1);
    head2 = reverseList(head2);

    //res应为局部变量 如果使用malloc分配 会存在内存泄漏 每次调用函数导致外部无法释放头节点
    //res为哨兵节点
    struct ListNode res;
    struct ListNode *phead = &res;

    int carry = 0;
    
    while(head1 != NULL || head2 != NULL || carry != 0){
        //只要链表不为空 进位还存在
        int val1 = (head1 == NULL ? 0 : head1->val);
        int val2 = (head2 == NULL ? 0 : head2->val);
        int temp = val1 + val2 + carry;

        //进位
        carry = temp / 10;
        //存储值
        temp = temp % 10;

        phead->next = malloc(sizeof(struct ListNode));
        if(phead->next == NULL)
        {
            return NULL;
        }
        phead = phead->next;
        //保存
        phead->val = temp;

        //移动下一个
        if(head1 != NULL){
            head1 = head1->next;
        }

        if (head2 != NULL) {
            head2 = head2->next;
        }

    }

    return reverseList(res.next);

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值