LeetCode:NO.2 Add Two Numbers

版权声明:本博全为博主学习日常,均为原创,请勿转载 https://blog.csdn.net/weixin_44332298/article/details/85540860

题目描述

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
Explanation: 342 + 465 = 807.

算法分析

两个链表表头对齐,同时向后遍历,对应结点相加存到新链表的对应位置,并用标志位记录进位信息。
1.如果链表l1比l2长,则继续遍历l1,并加上进位
2.如果链表l2比l1长,则继续遍历l2,并加上进位
注*:因为链表内容需要逆序存储,所以先处理个位再依次处理十位、百位等并使用尾插法插入新结点

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    ListNode *head = (ListNode *)malloc(sizeof(ListNode));
    ListNode *pre = head;
    ListNode *node = NULL;
    //进位
    int c = 0,sum;       //sum记录新链表每个结点的值
    //加法
    while(l1 != NULL && l2 != NULL){
        sum = l1->val + l2->val + c;
        c = sum / 10;
        node = (ListNode *)malloc(sizeof(ListNode));
        node->val = sum % 10;
        node->next = NULL;
        //尾插法
        pre->next = node;
        pre = node;
        l1 = l1->next;
        l2 = l2->next;
    }
    //例如:2->4->3->1   5->6->4
    while(l1 != NULL){
        sum = l1->val + c;
        c = sum / 10;
        node = (ListNode *)malloc(sizeof(ListNode));
        node->val = sum % 10;
        node->next = NULL;
        //尾插法
        pre->next = node;
        pre = node;
        l1 = l1->next;
    }
    //例如:2->4->3   5->6->4->1
    while(l2 != NULL){
        sum = l2->val + c;
        c = sum / 10;
        node = (ListNode *)malloc(sizeof(ListNode));
        node->val = sum % 10;
        node->next = NULL;
        //尾插法
        pre->next = node;
        pre = node;
        l2 = l2->next;
    }
    //最后一位还有进位
    if(c > 0){
        node = (ListNode *)malloc(sizeof(ListNode));
        node->val = c;
        node->next = NULL;
        //尾插法
        pre->next = node;
        pre = node;
    }
    return head->next;
}
};

运行结果

Mr.Y&M运行结果

猜你喜欢

转载自blog.csdn.net/weixin_44332298/article/details/85540860