题目
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
分析
创建head0作为伪头结点。
如果cur.next.val=cur.next.next.val,那么删除cur.next
代码
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)
return null;
ListNode head0=new ListNode(0,head);
ListNode cur=head0;
while(cur.next!=null&&cur.next.next!=null){
//需要删除cur.next
if(cur.next.val==cur.next.next.val){
int x=cur.next.val;//因为cur.next会变化,所以需要用变量来保存它
//退出循环时,2.cur.next不是x了,说明值为x的重复节点都已经删光了
while(cur.next!=null&&cur.next.val==x){
cur.next=cur.next.next;
}
}
else{
cur=cur.next;
}
}
return head0.next;
}
}
复杂度
时间复杂度:O(n),其中 n 是链表的长度。
空间复杂度:O(1)。