题解 | #删除链表中重复的结点#
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
ListNode head = new ListNode(0);
head.next = pHead;
ListNode pre = head;
ListNode cur = pHead;
while(cur != null){
while (cur.next != null && cur.val == cur.next.val) {
cur = cur.next; // 跳过重复的节点
}
// 如果pre的下一个节点就是cur,说明cur(及其之前的节点)没有重复
if (pre.next == cur) {
pre = pre.next;
} else {
// 跳过所有重复的节点,将pre直接连接到cur的下一个节点(即第一个不重复的节点)
pre.next = cur.next;
}
cur = cur.next; // 继续遍历
}
return head.next;
}
}
