Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List II.png

解題思路 :

這題的陷阱是在出現重複的點的時候 要把存有這個值的所有點都刪掉 (包含第一個) 所以還是使用 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;
}

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容