题解 | 删除有序链表中重复的元素-II
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
import java.util.*;
/**
因为链表是升序的,所以重复元素一定是连续的。
1.用 dummy 节点指向头,方便处理头节点可能被删除的情况。
2.用 pre 指向前一个不重复的节点(初始为 dummy)。
3.用 cur 指向当前节点。
4.当 cur 和 cur.next 值相等时,跳过所有相同值的节点。
5.如果不相等,则 pre 移动到下一个节点。
6.最后 pre.next 指向下一个不重复的节点。
*/
public class Solution {
public ListNode deleteDuplicates (ListNode head) {
if (head == null || head.next == null)return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
ListNode repeat=null;
while (cur != null) {
if(cur.next!=null&&cur.val==cur.next.val){
while(cur.next!=null&&cur.val==cur.next.val){
cur=cur.next;
}
cur=cur.next;
}else{
pre.next=cur;
pre=pre.next;
cur=cur.next;
}
}
pre.next = null;
return dummy.next;
}
}
