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
给定两个链表代表两个非负整数,数字被反向储存,每个节点中储存一个数字。求两个数的和并作为一个链表返回。
每两个节点求和生成一个新的节点,代码如下:
/**
* 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 *rootNode=new ListNode(0);
ListNode *pCurNode=rootNode;
int flag=0;
while (l1 || l2)
{
int v1=(l1?l1->val:0);
int v2=(l2?l2->val:0);
int temp=v1+v2+flag;
flag=temp/10;
ListNode *pNode=new ListNode(temp%10);
pCurNode->next=pNode;
pCurNode=pNode;
if (l1)
l1=l1->next;
if (l2)
l2=l2->next;
}
if (flag>0)
{
ListNode *pNode=new ListNode(flag);
pCurNode->next=pNode;
}
return rootNode->next;
}
};