思路:递归思路
每轮重复的话就跳过这个节点 这一轮存在重复,那么head直接重新来,等于拿新的节点来计算 如果这一轮不存在重复,那么head节点就是稳定的,从head.next开始计算
// @Title: 删除排序链表中的重复元素 II (Remove Duplicates from Sorted List II)
// @Author: qisiii
// @Date: 2024-01-14 16:46:32
// @Runtime: 0 ms
// @Memory: 42 MB
// @comment: 递归思路
每轮重复的话就跳过这个节点
这一轮存在重复,那么head直接重新来,等于拿新的节点来计算
如果这一轮不存在重复,那么head节点就是稳定的,从head.next开始计算
// @flag: WHITE
/**
* 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) {
if(head==null||head.next==null){
return head;
}
boolean repeat=false;
while(head!=null&&head.next!=null&&
head.val==head.next.val){
repeat=true;
head=head.next;
}
if(repeat){
head=head.next;
head=deleteDuplicates(head);
}else{
head.next=deleteDuplicates(head.next);
}
return head;
}
}
思路:
// @Title: 删除排序链表中的重复元素 II (Remove Duplicates from Sorted List II)
// @Author: qisiii
// @Date: 2024-01-15 09:47:27
// @Runtime: 0 ms
// @Memory: 42.2 MB
// @comment:
// @flag:
/**
* 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) {
if(head==null||head.next==null){
return head;
}
boolean repeat=false;
while(head!=null&&head.next!=null&&
head.val==head.next.val){
repeat=true;
head=head.next;
}
if(repeat){
head=head.next;
head=deleteDuplicates(head);
}else{
head.next=deleteDuplicates(head.next);
}
return head;
}
}