- 算法
- 1.设置伪结点,方便处理
- 2.双指针prev和curr
- 3.当遇到当前节点值和下一节点值相等的节点时,进行while循环找到下一个不相等的节点,挂到prev节点上
- 4.当遇到当前节点值和下一节点值不相等的节点时,prev和curr都移动到下一个节点接着遍历就行
public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode prev = dummy; ListNode curr = head; while (curr != null && curr.next != null) { if (curr.val == curr.next.val) { ListNode temp = curr.next; while (temp != null && temp.val == curr.val) { temp = temp.next; } prev.next = temp; curr = temp; } else { prev = prev.next; curr = curr.next; } } return dummy.next; }