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.

For example,
Given 1->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 }
View Code

 

 

 

posted @ 2014-02-06 14:45  krunning  阅读(111)  评论(0编辑  收藏  举报