链接: 删除排序链表中的重复元素 II
给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例 1:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3]
输出:[2,3]
提示:
[0, 300]
内-100 <= Node.val <= 100
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
int repeatValue = 101;
ListNode node = head;
ListNode beforeNode = null;
while (node != null) {
// 判断重复
if (repeatValue != node.val && node.next != null && node.val == node.next.val) {
repeatValue = node.val;
}
// 移除
if (node.val == repeatValue) {
if (beforeNode == null) {
head = node.next;
} else {
beforeNode.next = node.next;
}
} else {
beforeNode = node;
}
node = node.next;
}
return head;
}
}
整理完毕,完结撒花~ 🌻