Remove Duplicates From Sorted List II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Remove Duplicates From Sorted List II相关的知识,希望对你有一定的参考价值。

First we need to get the head node, use a boolean value to mark whether we find a new head or not. When we traverse the linked list, 

if(cur.val != cur.next.val && flag){
newHead = cur;
flag = false;
}

Once we find the first non-duplicative node, set that node to be head, and flag is false, meaning that we already find the head node, no need to find a new head anymore.

 

Use a pointer to record the previous node that ahead of the duplicative nodes, use the while loop

while(cur != null && cur.next != null && cur.val == cur.next.val) cur = cur.next;

to get the last node of the duplicative nodes. Then the cur = cur.next; can find the first node after the duplicative nodes, let prev.next = cur.

 

after the while loop, we need to check whether we already find a new head. If not, set the current node(maybe null) to be the head.

 

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode cur = head;
        ListNode prev = head;
        ListNode newHead = head;
        boolean flag = true;
        while(cur != null && cur.next != null){
            if(cur.val != cur.next.val && flag){
                newHead = cur;
                flag = false;
            }
            if(cur.val != cur.next.val) prev = cur;
            while(cur != null && cur.next != null && cur.val == cur.next.val) cur = cur.next;
            cur = cur.next;
            prev.next = cur;
        }
        if(flag) return cur;
        return newHead;
    }
}

 

以上是关于Remove Duplicates From Sorted List II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 26. Remove Duplicates from Sorted Array 80. Remove Duplicates from Sorted Array II

26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

#26 Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array [Python]