給定一個排序鏈表,刪除所有含有重複數字的節點,只保留原始鏈表中 沒有重複出現 的數字。
簡要題解:
設置雙指針遍歷一整個鏈表遇到重複的就把當前節點接到下一個節點。當前節點位置不變以防下一段還遇到重複的。主要代碼如下:
/**
* 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) {
ListNode* cur=new ListNode(0);
cur->next=head;
head=cur; ListNode *l,*r;
while(cur->next)
{
l=cur->next;
r=cur;
while(r->next&&r->next->val==l->val)
r=r->next;
if(l==r)cur=cur->next;
else cur->next=r->next;
}
return head->next;
}
};