Sunday, February 16, 2014

Remove Duplicates from Sorted List II @LeetCode

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.

package leetcode.linkedlist;
/**
* Solution: Use Dummy Node to handle the head change.
*
* Difference between II and I is the head will not change even duplicates in I, but will change in II(remove all same).
* So we need dummy node to delete head node, In addition, we need to remember the value of duplicate node.
* Usually, only head changes, we use dummy node. We can't change dummy in progress, because it points to head we will return at last.
*
* Take care:
* int val = head.next.val must use while delete this value at once.
* head = head.next must be wrapped by else, or it may head.next == null, and next loop. null.next leads NullPointer Problem.
* This is not same as removeduplicate I, while condition is not same.
*
*
* @author jeffwan
* @date Feb 16, 2014
*/
public class DeleteDuplicates2 {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
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) {
int val = head.next.val;
while (head.next != null && head.next.val == val) {
head.next = head.next.next;
}
} else {
head = head.next;
}
}
return dummy.next;
}
class ListNode {
int val;
ListNode next;
ListNode (int x) {
this.val = x;
}
}
}

No comments:

Post a Comment