删除排序的链表代码中的重复项不起作用。这是什么错误?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL || head->next==NULL)return head;
ListNode* curr=head;
while(curr!=NULL)
{
while(curr->val==curr->next->val){
curr->next=curr->next->next;
}
curr=curr->next;
}
return head;
}
};
您对删除重复项的逻辑有疑问。将您的while
循环更改为此:
while (curr != NULL) {
ListNode* index = curr;
while (curr->val == index->next->val) { // check for multiple possible duplicates
index = index->next; // and advance index to last duplicate
}
curr->next = index->next; // splice out the duplicate (if it exists)
curr = curr->next; // advance pointer
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句