题目:
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(-);//头节点
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=;//进位值
p=head.next;
ListNode *q=NULL;
for(;p;q=p,p=p->next)//处理进位
{ int a=(p->val)+d;
d=(a)/;
p->val = (a)%;
}
if(d>) //最高位有进位,则新建一个节点,如果不new,则函数结束时内存会被释放掉
{
//ListNode *l3=new ListNode(d);
q->next=new ListNode(d);
}
return l1;
}
};