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。但是我开始使用了申请空间函数
ans = ans->next = (ListNode *)malloc(sizeof(ListNode));
结果一直超时,malloc函数耗费时间过长,所以参考
http://blog.csdn.net/cmershen/article/details/51548614?locationNum=12&fps=1中的方法,让结果先随便等于l1和l2中不为空的一个,每次申请空间的部分都换成等于l1或l2中不为空的那个,所以可以保证答案的长度与l1和l2中最长的那个保持相等。如果最后有进位则再添加一位。
结论:1.用减法替换取模会快一些;
2.用别的方法替代malloc函数申请空间;
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* temp = l1 ? l1 : l2;
ListNode* ans = temp;
int flag = 0;
int s = 0;
while(l1 || l2){
//ans = ans->next = (ListNode *)malloc(sizeof(ListNode));
s = flag;
if(l1){
s += l1->val;l1 = l1->next;
}
if(l2){
s += l2->val;l2 = l2->next;
}
flag = s>9 ? 1 : 0;
ans->val = flag ? s-10 : s;
//保证ans与l1、l2中最长的保持一致长度,因为l1和l2也在向后移位
if (l1) {
ans = ans->next = l1;
} else if (l2) {
ans = ans->next = l2;
} else {
ans->next = NULL;
}
}
if(flag){
ans->next = (ListNode *)malloc(sizeof(ListNode));
ans = ans->next;
ans->val = flag;
}
ans->next = NULL;
// temp = temp->next;
return temp;
}