2. Add Two Numbers

来源:互联网 发布:大力水手 知乎 编辑:程序博客网 时间:2024/06/17 11:40

题目

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

分析

用链表模拟两个数相加,类似于字符串模拟大整数加法,不用创建新的链表保存结果,可以直接在l1或者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) {        if(l1==NULL)            return l2;        if(l2==NULL)            return l1;        ListNode* head=l1;        ListNode* p=head;        int carry=0;        while(l1!=NULL&&l2!=NULL){//同时处理l1和l2,结果保存到l1上            int temp=l1->val+l2->val+carry;            carry=temp/10;            temp=temp%10;            p->val=temp;            if(p->next!=NULL){                p=p->next;            }            l1=l1->next;            l2=l2->next;        }        while(l1!=NULL&&carry!=0){//l1未加完时,结果直接加到l1上,直到进位为0或者l1到头            int temp=l1->val+carry;            carry=temp/10;            temp=temp%10;            p->val=temp;            if(p->next!=NULL){                p=p->next;            }            l1=l1->next;        }        if(l2!=NULL){//当l2未加完时,p后接l2的剩余部分,然后将进位不断加到l2上            p->next=l2;//p与l2相连            p=p->next;//p指向l2剩余部分的第一个节点            while(carry!=0){                int temp=p->val+carry;//以后的操作直接在p上进行                carry=temp/10;                temp=temp%10;                p->val=temp;                if(p->next!=NULL){//p不到末尾时,向后移动,到末尾时,跳出循环                    p=p->next;                }                else{                    break;                }            }        }        if(carry!=0){//当进位剩余时,需要创建节点保存进位            ListNode* t=new ListNode(carry);            p->next=t;        }        return head;//返回结果链表的头指针    }};