题目连接:Add Two Numbers
//思路:两个指针分别遍历两个链表,用一个变量记录和,
//将得到的和加入到root链表尾部
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
//l1,l2为不带头结点的单链表
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *root = new ListNode(0);//带头结点的单链表
ListNode *p;
p = root;
int sum = 0;//和
while(l1 != NULL || l2 != NULL) {
if(l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if(l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
p->next = new ListNode(sum%10);
p = p->next;
sum /= 10;
}
if(sum) {
p->next = new ListNode(1);
}
return root->next;
}
};