您的位置:首页 > 其它

leetcode - Add Two Numbers

2014-09-05 10:24 309 查看
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,同时从头结点开始遍历两个链表,将对应的两个结点以及进位相加,和记为temp,进位记为flag,temp % 10是结果链表对应结点的值,temp / 10是进位flag

2,不断循环,直到某个链表遍历完,然后将未遍历完链表的剩余部分与进位相加,处理方式同1,直到该链表也遍历完

3,注意一下最后的进位flag是否为1,为1则表示最后结点的和是有进位的,需要再向高位进1

代码:

#include <stddef.h>

struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if (!l1)
{
return l2;
}

if (!l2)
{
return l1;
}

ListNode *l1Current = l1;
ListNode *l2Current = l2;
ListNode *result = NULL;
ListNode *head = NULL;
int flag = 0; //进位
int temp = 0;

while (l1Current && l2Current)
{
temp = l1Current->val + l2Current->val + flag;
if (result)
{
result->next = new ListNode(temp % 10);
result = result->next;
flag = temp / 10;
}
else
{
result = new ListNode(temp % 10);
head = result;
flag = temp / 10;
}
l1Current = l1Current->next;
l2Current = l2Current->next;
}

while (l1Current)
{
temp = l1Current->val + flag;
result->next = new ListNode(temp % 10);
result = result->next;
flag = temp / 10;
l1Current = l1Current->next;
}

while (l2Current)
{
temp = l2Current->val + flag;
result->next = new ListNode(temp % 10);
result = result->next;
flag = temp / 10;
l2Current = l2Current->next;
}

if (flag) //最后的结点和有进位
{
result->next = new ListNode(1);
}

return head;
}
};


View Code

网上基本是这个思路
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: