您的位置:首页 > 其它

两个链表的数字相加(简单题) add two numbers

2013-10-03 12:32 561 查看
题目: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.

一开始又理解错题意了!所以的数字都是小数点之后的。
做对的关键就是要彻底理解题意!!不要着急下手!

我开始的想法太复杂了。其实这道题思想没那么复杂。 也许是题目用“小数点”这个概念描述,有点过重了吧。

这题简单在于加法是向左对齐的。也就是链表开始就是对齐的。如果末端不齐的话,多出来的一边自己和进位相加即可。比较简单。

代码一:

class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sum, carry=0;
sum = l1->val + l2->val;
if(sum > 9)
{
sum -= 10;
carry = 1;
}
else
{
carry = 0;
}
ListNode *p = new ListNode(sum);
ListNode *l3 = p;

l1 = l1->next;
l2 = l2->next;
while((l1!=NULL)&&(l2!=NULL))
{
sum = l1->val + l2->val + carry;
ListNode *q = new ListNode(0);
if(sum > 9)
{
q->val = sum - 10;
carry = 1;
}
else
{
q->val = sum;
carry = 0;
}
p->next = q;
p = q;

l1 = l1->next;
l2 = l2->next;
}

while(l1!=NULL)
{
sum = l1->val + carry;
if(sum > 9)
{
sum -= 10;
carry = 1;
}
else
{
carry = 0;
}
ListNode *q = new ListNode(sum);
p->next = q;
p = q;
l1 = l1->next;
}

while(l2!=NULL)
{
sum = l2->val + carry;
if(sum > 9)
{
sum -= 10;
carry = 1;
}
else
{
carry = 0;
}
ListNode *q = new ListNode(sum);
p->next = q;
p = q;
l2 = l2->next;
}

if(carry==1)
{
ListNode *q = new ListNode(1);
q->next = NULL;
p->next = q;
}
return l3;
}
};


代码二:优化方法,一方面,为新链表创建一个空头结点,这样在加法操作上可以保持一致性。另一方面,为缩小代码量,只用一个循环来做遍历。
/**
* 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) {
ListNode head(0);
ListNode *p = &head;
int carry = 0;
int sum, v1, v2;
while(l1 != NULL || l2 != NULL)
{
if(l1 != NULL)
{
v1 = l1->val;
l1 = l1->next;
}
else
v1 = 0;

if(l2 != NULL)
{
v2 = l2->val;
l2 = l2->next;
}
else
v2 = 0;

sum = v1 + v2 + carry;
if(sum >= 10)
{
sum -= 10;
carry = 1;
}
else
carry = 0;

p->next = new ListNode(sum);
p = p->next;
}
if(carry == 1)
p->next = new ListNode(1);
return head.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: