这是我从排序链表中删除重复项的程序。我从链表的头节点遍历并使用 temp1 变量,我正在检查是否有任何相同值的重复项。如果我们找到与当前节点不同的数据,那么我们将其链接到当前节点并使其成为当前节点并重复该过程。 这是问题:- https://leetcode.com/problems/remove-duplicates-from-sorted-list/
ListNode* deleteDuplicates(ListNode* head) {
ListNode *curr=head,*temp1,*forw;
while(curr!=NULL)
{
//temp1 checks for next distinct element
temp1=curr->next;
while(temp1!=NULL)
{
//checking if the value at temp1 is distinct from current
if(temp1->val!=curr->val)
{
forw=temp1; //stored the distinct value in forw for reference to curr
break;
}
temp1=temp1->next;
}
curr->next=forw; // linked the distinct value to current
curr=curr->next;
}
return head;
}
但是,程序给出了 TLE(Time Limit Excedeed) 错误。我已经试运行了代码,它对我来说工作正常。我想我缺少一些优势。任何帮助将不胜感激?
答案 0 :(得分:3)
您有一个元素列表的 UB,因为 forw
然后未初始化使用。
(在你的情况下,UB 可能应该做无限循环,所以 TLE)。