LeetCode(Add Two Numbers)
阿新 • • 發佈:2019-01-13
一、題目要求
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.
二、解法
C語言
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* addTwoNumbers(structListNode* l1, struct ListNode* l2) { 9 struct ListNode* p1 = l1, *p2 = l2; 10 struct ListNode* new_node = 0; 11 struct ListNode* ret_node = 0; 12 struct ListNode* temp_node = 0; 13 int sum = 0; 14 15 while(p1 != NULL || p2 != NULL || sum != 0) { 16 int temp = (p1 ? p1->val : 0) + (p2 ? p2->val : 0) + sum; 17 int val = temp % 10; 18 sum = temp / 10; 19 20 new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); 21 new_node->val = val; 22 new_node->next = 0; 23 24 if (0 == temp_node) { 25 temp_node = new_node; 26 ret_node = temp_node; 27 } else { 28 temp_node->next = new_node; 29 temp_node = new_node; 30 } 31 32 p1 = p1 ? p1->next : p1; 33 p2 = p2 ? p2->next : p2; 34 } 35 return ret_node; 36 }
分析:根據題目的要求,將連結串列中對應元素相加,最後,倒序輸出為一個連結串列結構。
需要注意:
- 連結串列長度不相同情況,比如一個[1,2,3],例外一個是[1,2,3,4,5,6]情況時,實現方法:
p1 ? p1->val : 0
- 考慮進位情況,實現方法:
int temp = (p1 ? p1->val : 0) + (p2 ? p2->val : 0) + sum; int val = temp % 10; sum = temp / 10;
- 考慮輸出連結串列順序問題,實現方法:
if (0 == temp_node) { temp_node = new_node; ret_node = temp_node; } else { temp_node->next = new_node; temp_node = new_node; }
執行結果: