题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024?tpId=196&rp=1&ru=%2Fexam%2Foj&qru=%2Fexam%2Foj&sourceUrl=%2Fexam%2Foj&difficulty=&judgeStatus=&tags=&title=&gioEnter=menu
import java.util.*;
public class Solution {
public ListNode deleteDuplicates (ListNode head) {
// write code here
ListNode dummy = new ListNode(-1);
//如果要删除全部重复的。只保留独特的。需要一个辅助的节点
ListNode prev = dummy;
while (head!=null){
int cur = head.val;
int cnt = 1;
while (head.next!=null&&head.next.val == cur){
head = head.next;
cnt++;
}
// 1 1 2 3 4
// h
if (cnt==1){
prev.next = head;
prev = prev.next;
//prev.next = null;//这样不对,如果你这么写,就会把head的后面也断掉了。
//根本就不会遍历了
}else{
prev.next = head.next;//将prev的后续的节点更新为head的后面,
//去除重复的节点。
}
head = head.next;
}
return dummy.next;
}
}
