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.
首先想到能不能根据小学数学中两整数相加的过程,实现下。思考了下程序该怎么做。发现可以。
考虑几种情况,第一个链表的长度大于,小于,等于第二个链表,在最后末尾有无溢出。开始写下程序。
这里存在一个决定,是该选择第一个链表,还是选择第二个链表存储最终的结果。最好的选择是存在长的链表里,这样malloc申请的内存会少一些,减少空间占用。可是想要得到链表长度,需要n个步骤。
所以我就随机选了第一个链表,链表1大于链表2的概率是50%,我至少有一半的概率选到长的链表,而不需要计算两者的长度。我现在还不能下判断,到底哪种更好。
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 int overflow = 0, tmp; 10 struct ListNode *p1,*p2; 11 p1 = l1; 12 p2 = l2; 13 int i=1; 14 15 //process the one before the last one of common length 16 while(p1->next && p2->next) { 17 tmp = p1->val + p2->val + overflow; 18 overflow = tmp / 10; 19 p1->val = tmp % 10; 20 21 p1 = p1->next; 22 p2 = p2->next; 23 } 24 25 26 if (!p1->next) { //when length of l1 <= l2 27 tmp = p1->val + p2->val + overflow; 28 overflow = tmp / 10; 29 p1->val = tmp % 10; 30 31 //when l1 < l2 and no overflow. 32 if(!overflow && p2->next) { 33 p1->next = p2->next; 34 } 35 36 while (overflow) { 37 if (!p2->next){ 38 p2->next = malloc(sizeof(struct ListNode)); 39 memset(p2->next, 0, sizeof(struct ListNode)); 40 } 41 if(i==1) p1->next = p2->next; 42 i++; 43 p2 = p2->next; 44 tmp = p2->val + overflow; 45 overflow = tmp / 10; 46 p2->val = tmp % 10; 47 } 48 } else {//when legngth of l1 > l2 49 tmp = p1->val + p2->val + overflow; 50 overflow = tmp / 10; 51 p1->val = tmp % 10; 52 53 while (overflow) { 54 if (!p1->next) { 55 p1->next = malloc(sizeof(struct ListNode)); 56 memset(p1->next,0,sizeof(struct ListNode)); 57 } 58 p1 = p1->next; 59 tmp = p1->val + overflow; 60 overflow = tmp / 10; 61 p1->val = tmp % 10; 62 } 63 } 64 65 return l1; 66 67 }