[LintCode]Remove Duplicates from Sorted List II
Version 1
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of the linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
// 2015-08-18 思路更清晰
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head.next != null && head.next.next != null) {
if (head.next.val != head.next.next.val) {
head = head.next;
} else {
ListNode firstDup = head.next;
ListNode lastDup = head.next.next;
while(lastDup.next != null && lastDup.next.val == firstDup.val) {
lastDup = lastDup.next;
}
head.next = lastDup.next;
}
}
return dummy.next;
}
}
Version 2
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of the linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
// 2015-4-22 该方法比较繁琐,
// 引入了一个标志位dup,while中含三条分支,不推荐
if (head == null) {
return head;
}
boolean dup = false;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode last = dummy;
while (head.next != null) {
if (head.val != head.next.val && !dup) {
last = head;
head = head.next;
} else if (head.val != head.next.val && dup) {
dup = false;
last.next = head.next;
head = head.next;
} else { //head.val == head.next.val
dup = true;
head = head.next;
}
}
if (dup) {
last.next = null;
}
return dummy.next;
}
}