您的位置:首页 > 其它

Remove Duplicates from Sorted List II ——LeetCode

2015-06-07 22:35 387 查看
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
.

题目大意:给定一个有序的单链表,删除所有重复元素,只保留出现一次的。

解题思路:记录前驱节点,如果当前元素是重复的,直接把前驱节点的next指向后一个,循环一遍即可。代码写的还是很纠结。WA了五六次。

public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode dummy = new ListNode(0);
ListNode ptr = head;
while(head!=null){
ptr=head;
while(ptr.next!=null&&ptr.val==ptr.next.val){
ptr=ptr.next;
}
if(head!=ptr){
head=ptr.next;
}else{
break;
}
}
dummy.next=head;
ListNode tmp = head;
while(tmp!=null){
ptr=tmp.next;
if(ptr==null){
break;
}
while(ptr!=null&&ptr.next!=null&&ptr.val==ptr.next.val){
ptr=ptr.next;
}
if(ptr==tmp.next){
tmp=tmp.next;
continue;
}
tmp.next=ptr.next;
}
return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: