Leetcode 2 - Add Two Numbers

1.Question:

2. Add Two Numbers

 
  My Submissions
  • Total Accepted: 206533
  • Total Submissions: 804547
  • Difficulty: Medium
  • Contributors: Admin

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

2.Solution:

标准的链表的操作的题,本题我们模拟加法就可以了,注意进位,没有什么难的

3.Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* p=l1;
    struct ListNode* w=l2;
    int lenp=0;
    int lenw=0;
    while(p!=NULL) p=p->next,lenp++;
    while(w!=NULL) w=w->next,lenw++;
    p=l1;
    w=l2;
    //struct ListNode* h;
    int un=0;
    if(lenw>=lenp)
    {
        while(w!=NULL)
        {
            if(p!=NULL) w->val+=p->val+un;
            else w->val+=un;
            un=0;
            if(p!=NULL) p=p->next;
            if(w->val>=10) w->val-=10,un++;
            w=w->next;
        }
        if(un!=0)
        {
            w=l2;
            while(w->next!=NULL) w=w->next;
            struct ListNode* h=(struct ListNode*)malloc(sizeof(struct ListNode*));
            h->val=un;
            h->next=NULL;
            w->next=h;
        }
        return l2;
    }
    else
    {
        while(p!=NULL)
        {
            if(w!=NULL) p->val+=w->val+un;
            else p->val+=un;
            un=0;
            if(w!=NULL) w=w->next;
            if(p->val>=10) p->val-=10,un++;
             p=p->next;
        }
        if(un!=0)
        {
            p=l1;
            while(p->next!=NULL) p=p->next;
            struct ListNode* h=(struct ListNode*)malloc(sizeof(struct ListNode*));
            h->val=un;
            un=0;
            h->next=NULL;
            p->next=h;
        }
        return l1;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值