题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:首节点是可以删除的,因此需要定义一个新的头节点,之后就是判断当前节点是否重复,如果重复则跳过,我感觉需要注意的点是最后一个节点的next需要置为null
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null||pHead.next==null)return pHead;
ListNode root=new ListNode(-1);
ListNode first=root;
ListNode second=pHead;
while (second!=null){
if(second.next!=null&&second.next.val==second.val){
while (second.next!=null&&second.next.val==second.val){
second=second.next;
}
if(second.next==null)break;
second=second.next;
}else{
first.next=second;
first=first.next;
second=second.next;
}
}
first.next=null;
return root.next;
}
}