您的位置:首页 > 其它

leetcode 题解 Add Two Numbers(两个单链表求和)

2014-07-03 23:00 302 查看
题目:

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)和大数相加相似,数组换成单链表,注意单链表的操作,其他和大数求和方法相似:先对应为相加,再进行进位处理

/**
* 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(-1);//头节点
ListNode *p1=l1;
ListNode *p2=l2;
ListNode *p=&head;
while(p1&&p2)//每个对应节点值相加
{
p1->val=(p1->val)+(p2->val);
p->next=p1;
p=p1;
p1=p1->next;
p2=p2->next;
}
p->next = p1?p1:p2;
int d=0;//进位值
p=head.next;
ListNode *q=NULL;
for(;p;q=p,p=p->next)//处理进位
{

int a=(p->val)+d;
d=(a)/10;
p->val = (a)%10;
}
if(d>0) //最高位有进位,则新建一个节点,如果不new,则函数结束时内存会被释放掉
{
//ListNode *l3=new ListNode(d);
q->next=new ListNode(d);
}
return l1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: