LeetCode—82. Remove Duplicates from Sorted List II

Type:medium

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input:1->2->3->3->4->4->5Output:1->2->5

Example 2:

Input:1->1->1->2->3Output:2->3


给定一个排好序的链表,删去出现超过一次的所有节点。

判断head及head->next是否为空,若为空,返回head,结束。

首先设一个空的dummy节点指向head,用pre表示想要保留的节点,初始等于dummy,pre->next指向想要保留但未确定是否只出现一次的节点。cur指向当前遍历的节点。

当cur->next的val等于cur->val,cur向后遍历,直至cur-next-val不等于cur-val停止,此时判断pre-next是否与cur是同一个指针,若不等则pre-next指向cur-next,若相等则pre等于pre-next。最后返回dummy-next




ListNode* deleteDuplicates(ListNode* head) {

        if(!head || !head->next) return head;

        ListNode *dummy = new ListNode(-1);

        dummy->next = head;

        ListNode *pre = dummy;

        while(pre->next){

            ListNode *cur = pre->next;

            while(cur->next && cur->next->val == cur->val){

                cur = cur->next;

            }

            if(cur != pre->next) pre->next = cur->next;

            else pre = pre->next;

        }


        return dummy->next;

    }


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容