leetcode 2 -- Add Two Numbers

本文介绍了一种使用链表实现两个非负整数相加的方法。输入的两个链表分别存储了两个非负整数,数字以逆序方式存储,每个节点包含一个数字。通过遍历链表并逐位相加,考虑进位情况,最终得到的结果也以逆序形式存储在新的链表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

题意

两链表内各逆序保存一整数,将两整数相加之和逆序存于链表,返回该链表头指针

代码

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
   struct ListNode *p,*q,*head; 
    int num=0,c=0,i;
    p=l1;
    q=l2;
    while(1)
    {
        num++;//保存较短链表的长度
        p = p->next;
        q = q->next;
        if(q==NULL)//q指向长链表 p指向短链表
        {
            p=l2;
            q=l1;
            break;
        }
        if(p==NULL)
        {
            p=l1;
            q=l2;
            break;
        }
    }
    head=q;
    while(num--)//按位相加并进位
    {
        q->val += c + p->val;
        c = q->val /10;
        q->val %= 10;
        p=p->next;
        q=q->next;
    }  
    while(c)//若还有位未进
    {
        if(q==NULL)//q为NULL说明是最后一位 直接添加节点 赋值为1并break
        {
            p=(struct ListNode*)malloc(sizeof(struct ListNode));
            p->val=1;
            p->next=NULL;
            q=head;
            while(q->next!=NULL)
            {
                q=q->next;
            }
            q->next=p;
            break;
        }
        else
        {
            q->val += c;
            c = q->val /10;
            q->val %= 10;
            if(q->next == NULL && c)//为链表添加节点
            {
                p=(struct ListNode*)malloc(sizeof(struct ListNode));
                p->val=0;
                p->next=NULL;
                q->next=p;
                q=p;
            }
            else
            {
                q=q->next;
            }
        }
    }
    return head;
}

收获

添加节点时容易犯的逻辑错误
例:q为链表指针 此时 q->next = NULL;
错 : q=q->next; q=()malloc();
对 :p=()malloc(); q->next = p;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值