445. Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
题目要求:倒序将两链表的值相加,并加新链表倒序输出。
考察点:1.进位 2.两链表长短不一致的情况 3.链表的倒序 4.链表的建立
声明::关于2 & 4 ,有参考https://blog.csdn.net/godlovelong/article/details/70224437
My method
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode *node) {
struct ListNode *p = node, *q = node->next, *t;
while (p && q) {
t = q->next;
q->next = p;
p = q;
q = t;
}
node->next = NULL; //Do not forget! Or else p will loop
return p;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int last = 0; //进位
struct ListNode *t1, *t2;
struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode));
ret->val = 0;
struct ListNode *node = NULL;
t1 = (l1->next == NULL) ? l1 : (reverseList(l1));
t2 = (l2->next == NULL) ? l2 : (reverseList(l2));
while (t1 || t2 || last) {//t1有node 或 t2有node 或 还有进位
if (node == NULL) {
node = ret;
} else { //only malloc if the conditions are met
node->next = (struct ListNode *)malloc(sizeof(struct ListNode));//逐个node进行malloc
node->next->val = 0;
node = node->next;
}
int a = t1 ? t1->val : 0;
int b = t2 ? t2->val : 0;
node->val = (a + b + last) % 10;
last = (a + b + last) / 10;
node->next = NULL; //need set NULL to node->next in case the conditions are not met.
t1 = t1 ? (t1->next) : NULL;
t2 = t2 ? (t2->next) : NULL;
}
/*少考虑了还有进位的情况
while (t1) {
node->val = (t1->val + last) % 10;
last = (t1->val + last) / 10;
node->next = NULL;
t1 = t1->next;
}
while (t2) {
node->val = (t2->val + last) % 10;
last = (t2->val + last) / 10;
node = node->next;
t2 = t2->next;
}*/
return reverseList(ret);
}
特别声明:
关于处理两链表长短不一的情况以及新node的建立,有参考: https://blog.csdn.net/godlovelong/article/details/70224437