解答LeetCode82. 刪除排序鏈表中的重複元素 II

給定一個排序鏈表,刪除全部含有重複數字的節點,只保留原始鏈表中 沒有重複出現 的數字。指針

示例 1:code

輸入: 1->2->3->3->4->4->5
輸出: 1->2->5
示例 2:排序

輸入: 1->1->1->2->3
輸出: 2->3遞歸

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
 
            //對有重複數字的那一段進行處理
        if (head.next != null && head.val == head.next.val) {
            while (head != null && head.next != null && head.val == head.next.val) {
                head = head.next;
            }
            //去掉全部重複的數字,而後進行遞歸,最終結果使得頭指針指向去除重複數字後的的第一個數字
            return deleteDuplicates(head.next);
        } else {
            head.next = deleteDuplicates(head.next);
        }
        return head;


    }
}
相關文章
相關標籤/搜索