2. Add Two Numbers

題目

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;//返回結果鏈表的頭指針
    }
};


發佈了180 篇原創文章 · 獲贊 15 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章