您的位置:首页 > 其它

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的算法执行一遍即可

##代码
写一个翻转链表函数

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