题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
public ListNode deleteDuplicates (ListNode head) {
ListNode res=new ListNode(0);
res.next=head;
ListNode cur=res;
对头结点进行判定,若为空则返回null
if (head==null){
return null;
}
主体代码,对各个值进行比较,然后删除相同值节点
while (cur.next!=null&&cur.next.next!=null){
if (cur.next.val==cur.next.next.val){//循环条件
int tmp=cur.next.val;//把相同的值记下来
while (cur.next!=null&&cur.next.val==tmp) {//循环条件,利用虚拟节点可以一直指向不同的节点,并一直找到值不相同的点
cur.next = cur.next.next;
}
}else{
cur=cur.next;//不相同,将cur转向下一个节点前,继续循环
}
}
return res.next;//销毁虚拟节点
}
相关推荐
查看13道真题和解析