leetcode 2 -- Add Two Numbers

题目

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;

请赐予我钱进的动力吧~
0%