Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5
, return 1->2->5
.Given 1->1->1->2->3
, return 2->3
.
1 public class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if(head==null || head.next==null) return head; 4 ListNode safe = new ListNode(-1); 5 safe.next = head; 6 ListNode pre = safe; 7 ListNode cur = head; 8 ListNode post = head.next; 9 while(post!=null){10 if(post.val==cur.val){11 while(post!=null && post.val==cur.val){12 cur = post;13 post = post.next;14 }15 cur = post;16 if(post!=null)17 post = post.next;18 continue;19 }20 pre.next = cur;21 pre = cur;22 cur = post;23 if(post!=null)24 post = post.next;25 }26 pre.next = cur;27 return safe.next;28 }29 }