Remove Duplicates from Sorted List II
Source
- lintcode: Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have
duplicate numbers, leaving only distinct numbers from the original list.
Example
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Java
/**
* 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) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
//要同时check cur 和 cur.next 是不是null
while(cur!=null && cur.next!=null){
if(cur.val!=cur.next.val){
pre=pre.next;
cur=cur.next;
}
else{
while(cur.next!=null && cur.val==cur.next.val){
cur=cur.next;
}
pre.next=cur.next;
cur=cur.next;
}
}
return dummy.next;
}
}