Leetcode:2. Add Two Numbers(Week 6)

来源:互联网 发布:基于大数据用户画像 编辑:程序博客网 时间:2024/05/16 05:01

Description:

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

解题分析:

将两个非空链表从头到尾依次相加,得到一个新的链表,链表上的值为和的个位数,若和超过10则将和/10的结果(即进位)参与下一个节点的相加,重复上述操作直到较长链表结尾。

代码如下:

/** * 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 *prev = NULL, *result = NULL;        int carry = 0;        while (l1 || l2) {            int v1 = l1? l1->val : 0;            int v2 = l2? l2->val : 0;            int sum = v1+v2 + carry;            int value = sum%10;            carry = sum/10;            ListNode * cur = new ListNode(value);            if (!result) result = cur;            if (prev) prev->next = cur;            prev = cur;            l1 = l1 ? l1->next :NULL;            l2 = l2 ? l2->next : NULL;        }        if (carry > 0) {            ListNode * l = new ListNode(carry);            prev->next = l;        }        return result;    }};
原创粉丝点击