82. Remove Duplicates from Sorted List II

来源:互联网 发布:快易数据恢复 破解版 编辑:程序博客网 时间:2024/05/21 22:34

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.

代码:

public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return null;
ListNode FakeHead=new ListNode(0);
FakeHead.next = head;
ListNode pre = FakeHead;
ListNode cur = head;
while(cur!=null){
while(cur.next != null && cur.val == cur.next.val){
cur = cur.next;
}
if(pre.next == cur){ //注意是节点不是值
pre=pre.next;
}
else{
pre.next = cur.next;
}
cur = cur.next;
}
return FakeHead.next;
}
}

0 0
原创粉丝点击