1. 程式人生 > >(有部分參考)445. Add Two Numbers II

(有部分參考)445. Add Two Numbers II

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

題目要求:倒序將兩連結串列的值相加,並加新連結串列倒序輸出。

考察點:1.進位 2.兩連結串列長短不一致的情況 3.連結串列的倒序 4.連結串列的建立

My method

/**  * Definition for singly-linked list.  * struct ListNode {  *     int val;  *     struct ListNode *next;  * };  */ struct ListNode* reverseList(struct ListNode *node) {     struct ListNode *p = node, *q = node->next, *t;     while (p && q) {         t = q->next;         q->next = p;         p = q;         q = t;     }     node->next = NULL; //Do not forget! Or else p will loop

    return p; }

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {     int last = 0; //進位     struct ListNode *t1, *t2;     struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode));     ret->val = 0;     struct ListNode *node = NULL;          t1 = (l1->next == NULL) ? l1 : (reverseList(l1));     t2 = (l2->next == NULL) ? l2 : (reverseList(l2));     while (t1 || t2 || last) {//t1有node 或 t2有node 或 還有進位         if (node == NULL) {             node = ret;         } else { //only malloc if the conditions are met             node->next = (struct ListNode *)malloc(sizeof(struct ListNode));//逐個node進行malloc             node->next->val = 0;             node = node->next;         }         int a = t1 ? t1->val : 0;         int b = t2 ? t2->val : 0;         node->val = (a + b + last) % 10;         last = (a + b + last) / 10;         node->next = NULL; //need set NULL to node->next in case the conditions are not met.                  t1 = t1 ? (t1->next) : NULL;         t2 = t2 ? (t2->next) : NULL;          }     /*少考慮了還有進位的情況     while (t1) {         node->val = (t1->val + last) % 10;         last = (t1->val + last) / 10;         node->next = NULL;         t1 = t1->next;     }     while (t2) {         node->val = (t2->val + last) % 10;         last = (t2->val + last) / 10;         node = node->next;         t2 = t2->next;     }*/     return reverseList(ret); }

特別宣告: