1.描述
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
2.分析
3.代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* l = NULL;
struct ListNode* p = NULL;
struct ListNode* p1 = l1;
struct ListNode* p2 = l2;
int plus = 0;
while (p1 != NULL && p2 != NULL) {
struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
q->val = (p1->val + p2->val + plus) % 10;
q->next = NULL;
plus = (p1->val + p2->val + plus) / 10;
if (l == NULL) {
l = p = q;
}else {
p->next = q;
p = q;
}
p1 = p1->next;
p2 = p2->next;
}
while (p1 != NULL) {
struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
q->val = (p1->val + plus) %10;
q->next = NULL;
plus = (p1->val + plus) / 10;
p->next = q;
p = q;
p1 = p1->next;
}
while (p2 != NULL) {
struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
q->val = (p2->val + plus) %10;
q->next = NULL;
plus = (p2->val + plus) / 10;
p->next = q;
p = q;
p2 = p2->next;
}
while (plus != 0) {
struct ListNode* q = (struct ListNode*)malloc(sizeof (struct ListNode));
q->val = plus % 10;
q->next = NULL;
plus = plus/10;
p->next = q;
p = q;
}
return l;
}