Skip to main content

82 Remove Duplicates from Sorted List II

Leetcode

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

Example 1:

Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2:

Input: head = [1,1,1,2,3]
Output: [2,3]

使用头插法。使用一个指针,从头元素开始,如果指针下一个元素和下下个元素的值相同,while 循环,当指针的下一个元素的值和这个值相同时,指针的 next 只想下下个元素,知道元素为空或值不相同。

public ListNode deleteDuplicates(ListNode head) {
ListNode h=new ListNode();
h.next=head;
ListNode t=h;
while(t.next!=null && t.next.next!=null){
if(t.next.val==t.next.next.val){
int val=t.next.val;
while(t.next!=null && t.next.val==val){
t.next=t.next.next;
}
} else {
t=t.next;
}
}
return h.next;
}