题目:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析:此题可以用归并算法,但是有两点需要注意,1:如何记录首结点。。2:如何保持链表中的串接关系。。见代码注释。
代码1:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *pNode = NULL, *pNext = NULL, *pFirst = NULL; while(l1 != NULL && l2 != NULL){ int value = (l1->val + l2->val); if(pNext == NULL) // 不能进位 pNext = new ListNode(value%10); else{ // 有向前进位 pNext->val = (1+value)%10; value = value + 1; } if(value >= 10) // 大于10 向前进一位 pNext->next = new ListNode(1); if(pFirst == NULL) pFirst = pNode = pNext; // 存首结点 else{ pNode->next = pNext; // 保持串接关系 pNode = pNext; } pNext = pNext->next; l1 = l1->next; l2 = l2->next; } while(l1 != NULL){ int value = l1->val; if(pNext == NULL) pNext = new ListNode(value%10); else{ // 有向前进位 pNext->val = (1+value)%10; value = value + 1; } if(value >= 10) // 大于10 向前进一位 pNext->next = new ListNode(1); pNode->next = pNext; // 保持串接关系 pNode = pNext; pNext = pNext->next; l1 = l1->next; } while(l2 != NULL){ int value = l2->val; if(pNext == NULL) pNext = new ListNode(value%10); else{ // 有向前进位 pNext->val = (1+value)%10; value = value + 1; } if(value >= 10) // 大于10 向前进一位 pNext->next = new ListNode(1); pNode->next = pNext; // 保持串接关系 pNode = pNext; pNext = pNext->next; l2 = l2->next; } return pFirst; }以下这份代码是直接用pNode->next来保持串接进行的。
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *result = new ListNode(0); ListNode *pNode = result; bool flag = true; while(l1 != NULL && l2 != NULL){ int value = (l1->val + l2->val); if(result->next == NULL) result->next = new ListNode(value%10); else{ // 有向前进位 result->next->val = (1+value)%10; value = value + 1; } if(value >= 10) // 大于10 向前进一位 result->next->next = new ListNode(1); result = result->next; l1 = l1->next; l2 = l2->next; } while(l1 != NULL){ int value = l1->val; if(result->next == NULL) // 没有向前进位 result->next = new ListNode(value%10); else { result->next->val = (1+value)%10; value = value + 1; } if(value >= 10) result->next->next = new ListNode(1); result = result->next; l1 = l1->next; } while(l2 != NULL){ int value = l2->val; if(result->next == NULL) result->next = new ListNode(value%10); else { result->next->val = (1+value)%10; value = value + 1; } if(value >= 10) result->next->next = new ListNode(1); result = result->next; l2 = l2->next; } return pNode->next; }
原文地址:http://blog.csdn.net/lu597203933/article/details/44875613