题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
//1、先删除重复的后面元素,同 简单删除重复元素 算法
//2、删除第一个重复的元素。
//2.1、有过重复的元素 加标识;借助标识,head的前驱结点,删除当前head节点(当前head节点为第一个重复的节点)
//2.2、无重复的元素,前驱结点后移
//3、head结点重置为前驱节点的后一位
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if (head == null || head.next == null) {
return head;
}
ListNode res = new ListNode(-1);
res.next = head;
ListNode pre = res; //-1,1,1,1,2,3
boolean flag = false;
while (head != null && head.next != null) {
while (head.next!=null && head.val == head.next.val) { //1=1;1=1
head.next = head.next.next; //1,1,2,3; 1,2,3
flag = true;
}
if (flag) {
pre.next = head.next;//2,3
flag = false;
}else{
// head = head.next;//1,2,3---2.3
pre = pre.next;
}
head = pre.next;
}
return res.next;//-1,1,2,3
}
}
#算法题解#
查看4道真题和解析