2. Add Two Numbers LeetCode题解

来源:互联网 发布:2016电话数据资源购买 编辑:程序博客网 时间:2024/06/05 05:55

题目描述:

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.

题目大意:

给定两个非空链表代表两个非负整数。各个数位逆序排列并且每个节点保存一个数字。将两个数字相加,以链表形式返回。

你可以认为,两个数字除了0之外不包含前导0。

注:

逆序形式(2 -> 4 -> 3)代表342,数字逆序存储,每个节点存一个数位,同理(5 -> 6 -> 4)代表465

342+465=807表示为7 -> 0 -> 8

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

Subscribe to see which companies asked this question.


题解:

这是一道最基本的链表题,考察链表基本操作,以下几点值得注意:

1. 两个链表长度不一致情况的处理;

2. 生成新链表的长度较原l1和l2都长的情况(存在进位),比如5+5=10;


Code【Java】

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        // 创建dummy node节点        ListNode ans = new ListNode(0);        // 保存进位信息        int cnt = 0;        ListNode cur = ans;        for ( ; l1 != null || l2 != null; cur = cur.next) {            // l1 或 l2未到结尾时将相应的数位相加            if (l1 != null) {                cnt += l1.val;                l1 = l1.next;            }            if (l2 != null) {                cnt += l2.val;                l2 = l2.next;            }            // 当前结果保存在next中为cnt%10            cur.next = new ListNode(cnt % 10);            // 进位存在cnt中            cnt /= 10;        }        // 处理多余进位情况        if (cnt != 0) {            cur.next = new ListNode(cnt);        }        // 返回并未dummy node而是其下一个节点        return ans.next;    }}

Code【C++】

/** * 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) {        // 创建dummy node节点        ListNode ans(0);        // 保存进位信息        int cnt = 0;        ListNode* cur = &ans;        for ( ; l1 != NULL || l2 != NULL; cur = cur->next) {            // l1 或 l2未到结尾时将相应的数位相加            if (l1 != NULL) {                cnt += l1->val;                l1 = l1->next;            }            if (l2 != NULL) {                cnt += l2->val;                l2 = l2->next;            }            // 当前结果保存在next中为cnt%10            cur->next = new ListNode(cnt % 10);            // 进位存在cnt中            cnt /= 10;        }        // 处理多余进位情况        if (cnt != 0) {            cur->next = new ListNode(cnt);        }        // 返回并未dummy node而是其下一个节点        return ans.next;    }};


0 0