题解 | #牛群排列去重#
牛群排列去重
https://www.nowcoder.com/practice/8cabda340ac6461984ef9a1ad66915e4
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
// 1. 处理特殊情况
if (head == null || head.next == null) return head;
// 2. 遍历删除: 双指针删除
ListNode pre = head; // 前驱指针
ListNode cur = head.next; // 遍历指针
while (cur != null) { // 开始遍历
if (pre.val == cur.val){ // 如果发现有相同的进入循环寻找后续出现的第一个不同节点
while (cur != null && pre.val == cur.val) {
cur = cur.next;
}
pre.next = cur;// 将前驱节点指向后续出现的第一个不同的节点
} else {
pre = cur; // 如果前驱节点与当前节点不相同,则一起向后走
cur = cur.next;
}
}
// 3. 返回结果
return head;
}
}