解題思路 :
這題的陷阱是在出現重複的點的時候 要把存有這個值的所有點都刪掉 (包含第一個) 所以還是使用 dummy node 放在最前面連接原本的 head 來做 2 pointer 的掃描
C++ code :
<pre><code>
class Solution{
public:
/**
* @param head: The first node of linked list.
* @return: head node
*/
ListNode * deleteDuplicates(ListNode *head) {
// write your code here
if(!head) return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre = dummy;
while(head && head->next)
{
if(head->next->val != head->val)
{
pre = head;
head = head->next;
}
else
{
while(head->next && head->next->val == head->val)
{
head->next = head->next->next;
}
head = head->next;
pre->next = head;
}
}
return dummy->next;
}
};
网友评论