2. Add Two Numbers

1.描述

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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

2.分析

3.代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* l = NULL;
    struct ListNode* p = NULL;
    struct ListNode* p1 = l1;
    struct ListNode* p2 = l2;
    int plus = 0;
    while (p1 != NULL && p2 != NULL) {
        struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
        q->val = (p1->val + p2->val + plus) % 10;
        q->next = NULL;
        plus = (p1->val + p2->val + plus) / 10;
        if (l == NULL) {
            l = p = q;
        }else {
            p->next = q;
            p = q;
        }
        p1 = p1->next;
        p2 = p2->next;
    }
    
    while (p1 != NULL) {
        struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
        q->val = (p1->val + plus) %10;
        q->next = NULL;
        plus = (p1->val + plus) / 10;
        p->next = q;
        p = q;
        p1 = p1->next;
    }
    
    while (p2 != NULL) {
        struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
        q->val = (p2->val + plus) %10;
        q->next = NULL;
        plus = (p2->val + plus) / 10;
        p->next = q;
        p = q;
        p2 = p2->next;
    }
    
    while (plus != 0) {
        struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
        q->val = plus % 10;
        q->next = NULL;
        plus = plus/10;
        p->next = q;
        p = q;
    }
    
    return l;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • You are given two non-empty linked lists representing two...
    xxx亦凡桑阅读 222评论 0 0
  • 上通信的课就跟室友一起刷题玩,结果读题目读了半天,好歹我也是过了四级的人啊,怎么能这样,干脆百度题目意思…… 题目...
    做梦枯岛醒阅读 235评论 0 0
  • Description You are given two non-empty linked lists repr...
    CNSumi阅读 248评论 0 0
  • 澄清里,穿越千年的田螺 中国人吃田螺是有历史的。 田螺亦称螺蛳,是小吃中历史最为悠久的一鲜,拾食螺蛳的文字记载最早...
    LEMON_20e7阅读 1,626评论 0 0
  • 我叫唐龙,我出身一个在平凡不过的家庭。出生时没有天雷滚滚,晚霞夺天,可就几乎夺走我老妈的命,我是刨腹产,老妈生我3...
    找hui阅读 184评论 0 1