思路
- 需要新建一个头指针header, prev = header; nHead = pHead,以防链表第一个元素重复;
- 遍历链表当前值与next指针的值,若相同则循环直至不同,令prev.next指向当前指针的下一个;
- 反之若值不相同,prev.next指向该值,更新prev;
- 判断结束后,nHead = nHead.next
代码
public ListNode deleteDuplication(ListNode pHead)
{
ListNode header = new ListNode(-1);
header.next = pHead;
ListNode prev = header, nHead = pHead;
while(nHead != null && nHead.next != null){
if(nHead.val == nHead.next.val){
while(nHead.next != null && nHead.next.val == nHead.val){
nHead = nHead.next;
}
prev.next = nHead.next;
// 不要移动到下一个节点,因为有可能prev.next也是重复节点;如例子中4
// prev = prev.next;
}else{
prev.next = nHead;
prev = prev.next;
}
nHead = nHead.next;
}
return header.next;
}