leetcode上的算法题报错Submission Result: Time Limit Exceeded
leet算法题第二题,两个数字相加,通过链表的形式相加。
题目如下:
- 英文: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.
- 中文:给你两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。添加这两个数字并将其作为链接列表返回。 您可以假定这两个数字不包含任何前导零,除了数字0本身。
我的源码:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *t1,*t2,*new,*head,*hh;
t1 = l1;
t2 = l2;
int jinwei = 0;
new = malloc(sizeof(struct ListNode));
new->next = NULL;
head=new;
hh = head;
while(t1 && t2){
new->val = t1->val + t2->val + jinwei;
jinwei = new->val /10 ;
new->val = new->val %10;
t1 = t1->next;
t2 = t2->next;
new->next = head->next;
head->next = new;
head = head->next;
new = malloc(sizeof(struct ListNode));
}
if(t1==NULL && t2==NULL){
new->val = jinwei;
new->next = head->next;
head->next = new;
head = head->next;
}
else if(t2 != NULL ){
new = t2+jinwei;
}
else{
new = t1+jinwei;
}
return hh;
}
leetcode报错:
回答:
new->next = head->next; head->next = new;
head = head->next;
new = malloc(sizeof(struct ListNode));
运行中,此四行构造出一循环链表。故addTwoNumbers函数退出后,判定程序在打印结果时死循环。
以上是 leetcode上的算法题报错Submission Result: Time Limit Exceeded 的全部内容, 来源链接: utcz.com/p/194577.html