removeFromList

来源:互联网 发布:淘宝达人发布短视频 编辑:程序博客网 时间:2024/06/03 07:04

remove-duplicates-from-sorted-list:

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, return1->2->5.
Given1->1->1->2->3, return2->3.

package leetcode;

/*一般会修改链表头的题目使用一个辅助的空指针。
* */
public class RemoveAllFromList {
public ListNode deleteAllDulicates(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode helper=new ListNode(0);
helper.next=head;
ListNode pre=helper;
ListNode cur=head;
while(cur!=null){
while(cur.next!=null&&pre.next.val==cur.next.val){
cur=cur.next;
}
if(pre.next==cur){
pre=pre.next; // 将pre指向上一个非重复元素;
}
else{
pre.next=cur.next; //将重复的元素删除
}
cur=cur.next;
}
return helper.next;
}
}

这是有序链表,重复的元素都在一起。
把前驱指针指向上一个不重复的元素中,如果找到不重复元素,则把前驱指针知道该元素,否则删除此元素。

开始没有注意题目是有序链表,想了好久

原创粉丝点击