标签:
https://leetcode.com/problems/add-two-numbers/
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
最好是就地修改,这样只需要 O(1) 的额外空间。
尽量一次扫描就完成,时间复杂度 O(N)。
运行时间是 16ms
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { if (!l1) //如果输入l1就为空 { return l2; } struct ListNode *p1 = l1; struct ListNode *p2 = l2; int sum = 0; int carry = 0; while (p1) { sum = p1->val + carry; sum += p2 ? p2->val : 0; //sum = p1->val + p2->val(尝试) + carry carry = sum / 10; sum %= 10; p1->val = sum; if (!p1->next) //如果p1到头了 { if (p2 && p2->next) //如果p2没到头,就把p2后面的部分接到p1后面 { p1->next = p2->next; } else //如果p2也到头了,就检查有没有进位 { if (carry) //有进位就计算进位,新建一个节点 { struct ListNode *p_temp = (struct ListNode *)malloc(sizeof(struct ListNode)); p1->next = p_temp; p_temp->val = carry; p_temp->next = NULL; p1 = p_temp; carry = 0; } } p1 = p1->next; //已经尽力让p1继续下去 p2 = NULL; //p2不管之前怎样,到这里都是NULL了 } else //如果p1没到头 { p1 = p1->next; //p1继续前进 p2 = p2 ? p2->next : NULL; //p2尝试继续前进 } } return l1; }
查看自己用 C++ 写的以前版本的代码,是先新建了一个链表存放结果,因为使用头插法,所以最后还需要反转结果链表,甚至还产生了头结点的内存泄漏,这样的时间复杂度是 O(N)(常数项会大一些),空间复杂度也是 O(N),代码质量较差。
运行时间是 68ms
//反面教材 class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode head(0); head.next = NULL; int addition = 0; while ((l1 != NULL) || (l2 != NULL)) { int l1Val, l2Val; if (l1 != NULL) { l1Val = l1->val; l1 = l1->next; } else { l1Val = 0; } if (l2 != NULL) { l2Val = l2->val; l2 = l2->next; } else { l2Val = 0; } addition += l1Val + l2Val; ListNode * pTemp = new ListNode(addition % 10); addition /= 10; pTemp->next = head.next; head.next = pTemp; } if (addition != 0) { ListNode * pTemp = new ListNode(addition); pTemp->next = head.next; head.next = pTemp; } return reverseNode(head.next); } ListNode * reverseNode(ListNode *first) { ListNode head(0); head.next = NULL; ListNode * p = first; while (p) { ListNode * pre = p->next; p->next = head.next; head.next = p; p = pre; } return head.next; } };
标签:
原文地址:http://www.cnblogs.com/intervention/p/4608869.html