2. Add Two Numbers 链表表示的两数求和

2017-07-31  本文已影响0人  这就是一个随意的名字

You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
给定两个代表两个非负数的链表,按数位逆置方式存储(即123存储为3→2→1→NULL),要求返回两数之和的链表。


思路:
【方法1】将两个链表转换为整数,相加后再转换为链表返回,需要注意int型表示的范围,必要时需要使用long int或longlong;

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(!l1 || !l2)  return(!l1)?l2:l1;

        long int n1=0,n2=0,n3=0,digit=0,count=1;
        ListNode *p=l1;
        while(p){
            digit=p->val;
            n1=n1+digit*count;
            p=p->next;
            count*=10;
        }
        p=l2;
        count=1;
        while(p){
            digit=p->val;
            n2=n2+digit*count;
            p=p->next;
            count*=10;
        }

        n3=n1+n2;
        ListNode *res=new ListNode(n3%10);
        n3/=10;
        p=res;
        for(;n3>0;n3/=10){
            ListNode *tmp=new ListNode(n3%10);
            p->next=tmp;
            p=tmp;
        }
        p->next=nullptr;
        return res;
    }
};

【方法2】直接在链表上进行处理,由于链表是逆序数位存储,相当于整数右对齐加法,相加时注意进位以及两数位数不一致的情况。
两种方法相比较而言方法1较为简单,但处理位数受限,耗时较长。

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode *head = NULL, *prev = NULL;
    int carry = 0;
    while (l1 || l2) {
        int v1 = l1? l1->val: 0;
        int v2 = l2? l2->val: 0;
        int tmp = v1 + v2 + carry;
        carry = tmp / 10;
        int val = tmp % 10;
        ListNode* cur = new ListNode(val);
        if (!head) head = 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 head;
}
上一篇下一篇

猜你喜欢

热点阅读