leetcode 002-Add Two Numbers

problem:

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.

example:

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

note:

hint:

  • 用int或long來(lái)存儲(chǔ)兩個(gè)鏈表顯然會(huì)產(chǎn)生溢出
  • 定義一個(gè)變量來(lái)判斷是否存在進(jìn)位

code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int len,flag,i,temp;
    int* num = (int*)malloc(1000*sizeof(int));
    temp = 0;              //temp保存是否存在進(jìn)位
    len = 0;              //len表示兩個(gè)整數(shù)相加最后的總長(zhǎng)度
    while(l1 && l2){  //當(dāng)兩個(gè)數(shù)可以相加時(shí)的計(jì)算
        num[len++]=(l1->val+l2->val+temp)%10;
        temp = (l1->val+l2->val+temp)/10;
        l1 = l1->next;
        l2 = l2->next;
    }
    while(l1){      //當(dāng)l2為空時(shí),只計(jì)算l1和進(jìn)位之間的和
        num[len++]=(l1->val+temp)%10;
        temp = (l1->val+temp)/10;
        l1 = l1->next;
    }
    while(l2){
        num[len++]=(l2->val+temp)%10;
        temp = (l2->val+temp)/10;
        l2 = l2->next;
    }
    if(temp!=0){  //判斷是否還存在進(jìn)位
        num[len++] = temp;
    }
    
    flag = 1;        //沒(méi)有頭結(jié)點(diǎn)的存在,故判斷添加的節(jié)點(diǎn)是否為首元節(jié)點(diǎn)
    
    struct ListNode *l,*r;
    r = l;    //r指針用于定位鏈表的最后一個(gè)元素
    for(i = 0;i<len;i++){
        struct ListNode *s = (struct ListNode*)malloc(sizeof(struct ListNode));    //定義一個(gè)節(jié)點(diǎn)來(lái)存儲(chǔ)新的元素
        s->val = num[i];
        s->next = NULL;
        if(flag){
            l = s;
            flag = 0;
        }else{
            r->next = s;
        }
        r = s;
    }
    return l;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容