您的位置:首页 > 其它

Remove Duplicates from Sorted List II

2014-02-06 14:45 302 查看
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
.

public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null) return head;
ListNode safe = new ListNode(-1);
safe.next = head;
ListNode pre = safe;
ListNode cur = head;
ListNode post = head.next;
while(post!=null){
if(post.val==cur.val){
while(post!=null && post.val==cur.val){
cur = post;
post = post.next;
}
cur = post;
if(post!=null)
post = post.next;
continue;
}
pre.next = cur;
pre = cur;
cur = post;
if(post!=null)
post = post.next;
}
pre.next = cur;
return safe.next;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: