码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-2 Add Two Numbers

时间:2018-10-27 15:22:19      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:single   output   部分   node   pre   tput   null   self   code   

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
想法:这题思路很清晰,逐个节点相加即可,但是需要注意到结果大于9,会存在进位的问题,因而需要设置变量jinwei来保存这个进位信息。还得考虑到两个链表非等长的情况,这时处理完两个链表共有的部分之后,单独处理剩下的链表,这个时候仍有会有进位的信息存在。
/**
 * 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* q = l2;
    struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* r = temp;
    int jinwei = 0;//保存进位信息
//考虑两个链表共有的部分
    while(p && q){
        struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->val = (p->val + q->val + jinwei) % 10;
        jinwei = (p->val + q->val + jinwei) / 10;
        temp->next = t;
        temp = t;
        p = p->next;
        q = q->next;
    }
    
    while(p){
        struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->val = (p->val + jinwei)%10;
        jinwei = (p->val + jinwei)/10;
        temp->next = t;
        temp = t;
        p = p->next;
    }
    while(q){
        struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->val = (q->val+jinwei)%10;
        jinwei = (q->val+jinwei)/10;
        temp->next = t;
        temp = t;
        q = q->next;
    }
//如若所有节点处理完之后,仍然还有进位信息存在,则需要另外申请节点储存该信息
    if(jinwei!=0){
        struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->val = jinwei;
        temp->next =t;
        temp = t;
    }
    temp->next = NULL;
    return r->next;
    
}

leetcode-2 Add Two Numbers

标签:single   output   部分   node   pre   tput   null   self   code   

原文地址:https://www.cnblogs.com/tingweichen/p/9861268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!