[LeetCode]--83. Remove Duplicates from Sorted List

    xiaoxiao2025-08-23  6

    Firstly, see my ugly code!

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; ListNode curr = head; while (curr != null && curr.next != null){ if (curr.val == curr.next.val && curr.next.next != null) { curr.next = curr.next.next; // the 'continue' solve the problem that "11111" etc. continue; } else if (curr.val == curr.next.val && curr.next.next == null) { curr.next = null; } curr = curr.next; } return head; } }

    Recursive Solution(Excellent idea)\

    public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null)return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; }
    转载请注明原文地址: https://ju.6miu.com/read-1301945.html
    最新回复(0)