[leetcode] 学习记录——Add Two Numbers
2015-01-22 14:44
489 查看
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { } };
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.
numbers and return it as a linked list.
Input: (2
-> 4 -> 3) + (5 -> 6 -> 4)
Output: 7
-> 0 -> 8
分析:这是一道常规的链表操作题目,就是将342 + 465 = 807 的结果存于链表中。但是在做题过程中一开始 想的过于简单,只是想先将他们转化为数字再相加得到结果,存成链表。但是测试用例中有许多的大数,结果int超出表示范围。其实这个链表相加就是解决大数问题的,因为它已经逐位对其了,才用进位思想,代码可以写的非常巧妙。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { int c,n1,n2; c = 0; ListNode result(0); ListNode *p = &result; while(l1||l2||c){ n1= l1==NULL?0:l1->val; n2 = l2==NULL?0:l2->val; ListNode *t = new ListNode((c+n1+n2)%10); p ->next = t; p = p->next; c = (c+n1+n2)/10; l1 = l1==NULL?l1:l1->next; l2 = l2==NULL?l2:l2->next; } return result.next; } };
收获:
【1】 c++构造函数可以这样写
ListNode(int x) : val(x), next(NULL){}
表示给val 初始化为x,next指针初始化为NULL;
那么一开始声明变量时可以这样写 : ListNode result(0);
【2】遗忘的知识点:局部变量在函数返回的时候就会被释放掉,因此要new一个指针变量,来构造链表,这样return的时候链表是完整的。
【3】头指针技巧,由于循环的时候如果没有头指针,还要对第一个指针做特殊的判断和处理,但是有了头指针,就可以一概而论,并且return result.next即可(result声明为头指针)
【4】进位计算技巧,当前位 (c+n1+n2) /10 进位 c = (c+n1+n2) % 10
相关文章推荐
- 和大神们学习每天一题(leetcode)-Add Two Numbers
- 个人记录-LeetCode 2.Add Two Numbers
- Leetcode学习(25)—— Add Two Numbers
- leetCode刷题记录-2. Add Two Numbers
- leetcode 59: Add Two Numbers
- Leetcode : Add Two Numbers
- LeetCode4: Add Two Numbers
- [Leetcode 40] 1 Add Two Numbers
- [leetcode] Add Two Numbers *
- LeetCode Add Two Numbers
- leetcode Add Two Numbers
- leetcode - Add Two Numbers
- [面试真题] LeetCode:Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers, Solution
- LeetCode_Add Two Numbers
- LeetCode题目之5 Add Two Numbers
- 【leetcode】Add Two Numbers