Add Two Numbers(兩個連結串列求和)
阿新 • • 發佈:2019-01-08
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.
思路:遍歷連結串列的時候各位求和,大於10向高位進位,考慮兩個連結串列不一樣長的情況。
C:carry為進位標誌
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *l1_index,*l2_index,*l,*p; l = (struct ListNode*)malloc(sizeof(struct ListNode)); p = l; int carry = 0; l1_index = l1; l2_index = l2; while (l1_index != NULL || l2_index != NULL){ if(l1_index == l1 && l2_index == l2){ l->val = l1_index->val + l2_index->val; //進位標誌 if(l->val >= 10){ carry = 1; l->val %= 10; } l1_index = l1_index->next; l2_index = l2_index->next; continue; } if(l1_index == NULL){ //先建立一個節點 struct ListNode *q; q = (struct ListNode*)malloc(sizeof(struct ListNode)); p->next = q; p = q; p->val = l2_index->val + carry; if(p->val >= 10){ p->val %= 10; carry = 1; }else{ carry = 0; } l2_index = l2_index->next; continue; } else if(l2_index == NULL){ //先建立一個節點 struct ListNode *q; q = (struct ListNode*)malloc(sizeof(struct ListNode)); p->next = q; p = q; p->val = l1_index->val + carry; if(p->val >= 10){ p->val %= 10; carry = 1; }else{ carry = 0; } l1_index = l1_index->next; continue; } else{ //先建立一個節點 struct ListNode *q; q = (struct ListNode*)malloc(sizeof(struct ListNode)); p->next = q; p = q; p->val = l1_index->val + l2_index->val; p->val += carry; if(p->val >= 10){ p->val %= 10; carry = 1; }else{ carry = 0; } l1_index = l1_index->next; l2_index = l2_index->next; continue; } } if(carry == 1){ //先建立一個節點 struct ListNode *q; q = (struct ListNode*)malloc(sizeof(struct ListNode)); p->next = q; p = q; p->val = carry; } p->next = NULL; return l; }