Remove Duplicates from Sorted List II 解答

时间:2023-03-09 12:49:07
Remove Duplicates from Sorted List II 解答

Question

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Solution

Note here we need to consider head of the list. For example, for input 1 -> 1, we need to return null.

 /**
* 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) {
if (head == null || head.next == null)
return head;
while (head.next != null && head.val == head.next.val) {
while (head.next != null && head.val == head.next.val)
head = head.next;
if (head.next != null)
head = head.next;
else
return null;
}
ListNode current = head, next1, next2;
while (current != null && current.next != null && current.next.next != null) {
next1 = current.next;
next2 = current.next.next;
if (next1.val != next2.val) {
current = current.next;
} else {
while (next2 != null && next1.val == next2.val)
next2 = next2.next;
current.next = next2;
}
}
return head;
}
}