在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
方法:
尾插入法
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
ListNode res=new ListNode(-1);
ListNode tail=res,temp=pHead;
while(temp!=null){
if(temp.next!=null && temp.val==temp.next.val){ //当有重复的元素时,跳过重复的结点
while(temp.next!=null && temp.val==temp.next.val){ //找到最后一个重复结点
temp=temp.next;
}
temp=temp.next; //跳过重复结点
}else{ //此时结点不重复,尾插入
tail.next=temp;
tail=temp;
temp=temp.next;
}
}
tail.next=null; //最后结点置空
return res.next;
}
}