82. Remove Duplicates from Sorted List II
Problem Description
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Return the linked list sorted as well.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
Solution Method
在開頭重複元素卡了好久,定義一個啞節點,萬事皆休。
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if (head == NULL)
return NULL;
struct ListNode dummy; // 定義一個啞節點處理開始的重複
dummy.next = head;
dummy.val = -1;
struct ListNode *p = &dummy, *q = p->next, * r = q->next;
while (r != NULL)
{
if (q->val != r->val)
{
p->next = q;
p = q;
q = q->next;
}
else
{
// 跳過相同元素
while (r->val == q->val)
{
r = r->next;
if (r == NULL)
{
p->next = NULL;
return dummy.next;
}
}
// 刪除相同元素
q = r;
p->next = q;
}
r = r->next;
}
return dummy.next;
}