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(struct ListNode* 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 }
分析:根据题目的要求,将链表中对应元素相加,最后,倒序输出为一个链表结构。
需要注意:
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; }
运行结果:
原文:https://www.cnblogs.com/zou107/p/10261312.html