題目描述
在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5
代碼:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead == NULL || pHead == NULL) return pHead;
ListNode* Head = new ListNode(0);//添加頭結點防止出現前兩個元素就一致的情況
Head->next = pHead;
ListNode* low = Head;//慢指針
ListNode* high = Head->next;//快指針
while(high!=NULL)
{
if(high->next!=NULL && high->val == high->next->val)
{
//尋找最後一個重複元素的位置
while(high->next!=NULL && high->val == high->next->val)
{
high = high->next;
}
low->next = high->next;//刪除所有重複結點
high = high->next;
}
else
{
high = high->next;//否則雙指針同時向前走
low = low->next;
}
}
return Head->next;//返回頭結點下一結點,不能返回pHead
//原因:不能返回pHead的原因是如果測試用例爲1->1->1->1->1->2的話,最後結果鏈表會變成Head->2,而原來的頭指針pHead之後的元素並沒有斷鏈,所以如果如果返回pHead的話結果會和原來的鏈表一樣1->1->1->1->1->2
}
};