美文网首页
Remove Duplicates from Sorted Li

Remove Duplicates from Sorted Li

作者: 一枚煎餅 | 来源:发表于2016-10-10 04:05 被阅读0次
Remove Duplicates from Sorted List.png

解題思路 :

簡易的掃描只要任何一個 node 的下一個點 數值與他本身相同 就把下一個點刪掉 直接連到下下個點 一直到掃完整個 list 因為 head 可以永遠不被刪除 (遇到相同的保留第一個) 所以無需 dummy node 的建立來連接 head

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 *cur = head;
    while(cur->next)
    {
        if(cur->val == cur->next->val)
        {
            ListNode *tmp = cur->next;
            cur->next = cur->next->next;
            delete tmp;
        }
        else cur = cur->next;
    }
    return head;
}

};

相关文章

网友评论

      本文标题:Remove Duplicates from Sorted Li

      本文链接:https://www.haomeiwen.com/subject/qopmyttx.html