1. 程式人生 > >leetcode-2 Add Two Numbers

leetcode-2 Add Two Numbers

single round output num spa tor repr tro 情況

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
Explanation: 342 + 465 = 807.
想法:這題思路很清晰,逐個節點相加即可,但是需要註意到結果大於9,會存在進位的問題,因而需要設置變量jinwei來保存這個進位信息。還得考慮到兩個鏈表非等長的情況,這時處理完兩個鏈表共有的部分之後,單獨處理剩下的鏈表,這個時候仍有會有進位的信息存在。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 
*/ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode* p = l1; struct ListNode* q = l2; struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* r = temp; int jinwei = 0;//保存進位信息
//考慮兩個鏈表共有的部分
    while(p && q){
        
struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode)); t->val = (p->val + q->val + jinwei) % 10; jinwei = (p->val + q->val + jinwei) / 10; temp->next = t; temp = t; p = p->next; q = q->next; } while(p){ struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode)); t->val = (p->val + jinwei)%10; jinwei = (p->val + jinwei)/10; temp->next = t; temp = t; p = p->next; } while(q){ struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode)); t->val = (q->val+jinwei)%10; jinwei = (q->val+jinwei)/10; temp->next = t; temp = t; q = q->next; }
//如若所有節點處理完之後,仍然還有進位信息存在,則需要另外申請節點儲存該信息
    if(jinwei!=0){
        struct ListNode* t = (struct ListNode*)malloc(sizeof(struct ListNode));
        t->val = jinwei;
        temp->next =t;
        temp = t;
    }
    temp->next = NULL;
    return r->next;
    
}

leetcode-2 Add Two Numbers