LeetCode解题思路之Add Two Numbers II
2017-06-23 00:00
309 查看
##问题描述
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
与Add Two Numbers问题恰好相反,从右到左依次进行加法操作
##解题思路
可以将链表翻转,然后用Add Tow Numbers的算法执行一遍即可
##代码
写一个翻转链表函数
最后将输入的表翻转后用Add Tow Numbers的方法计算出结果,然后再翻转即可
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
与Add Two Numbers问题恰好相反,从右到左依次进行加法操作
##解题思路
可以将链表翻转,然后用Add Tow Numbers的算法执行一遍即可
##代码
写一个翻转链表函数
struct ListNode* reverse(struct ListNode* head) { struct ListNode* newHead = NULL; while (head) { if (NULL == newHead) { newHead = head; head = head->next; newHead->next = NULL; } else { struct ListNode* tmpNext = head->next; head->next = newHead; newHead = head; head = tmpNext; } } return newHead; }
最后将输入的表翻转后用Add Tow Numbers的方法计算出结果,然后再翻转即可
struct ListNode* reverse(struct ListNode* head); struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { l1 = reverse(l1); l2 = reverse(l2); struct ListNode* newList = addTwoNumbersEx(l1, l2); newList = reverse(newList); return newList; }
相关文章推荐
- LeetCode解题思路之 Add Two Numbers
- 【LeetCode】2.Add Two Numbers思路以及知识点复习
- [LeetCode]Add Two Numbers II
- [LeetCode] Add Two Numbers II 两个数字相加之二
- Sum—LeetCode-445 Add Two Numbers II
- LeetCode Add Two Numbers II
- 【leetcode 445】Add Two Numbers II
- Leetcode: Add Two Numbers II
- [leetcode解题]Add Two Numbers
- Leetcode Day6 2. Add Two Numbers I & II
- Add Two Numbers II ---LeetCode
- Add Two Numbers II || LeetCode-445
- LeetCode - 445 - Add Two Numbers II
- 2. Add Two Numbers解题思路
- 【LeetCode】Add Two Numbers 解题报告
- LeetCode-Add Two Numbers II
- leetcode 445 Add Two Numbers II C++
- LeetCode-Add Two Numbers-解题报告
- Leetcode 解题 Add Two Numbers Python
- 【LeetCode】2. Add Two Numbers 解题报告