【Leetcode】82. Remove Duplicates from Sorted List II

於淼發表於2018-02-25

Question:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Tips:
跟83題比較,本題需要刪除所有的重複數字,即只要一個數字出現重複,那麼總第一個該數字開始都將被刪除。
 
思路:
①設定一個新的頭結點newHead,以及一個pre結點一個cur結點。將pre初始化為newHead,在pre之後找到第一個不重複的結點,並將其賦值給pre.next。
②遞迴。找到第一個不重複的結點,將它的next結點遞迴。
 
程式碼:
public ListNode deleteDuplicates1(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode pre = newHead;
        ListNode cur = head;
        while (cur != null) {
            //找到第一個不重複的結點
            while (cur.next != null && cur.val == cur.next.val)
                cur = cur.next;
            //當pre的next就是cur即兩者之間沒有重複數字,將pre指標後移即可。
            if (pre.next == cur) {
                pre = cur;
            } else
                //否則 跳過cur 將pre的next設定成cur的next
                pre.next = cur.next;
            cur = cur.next;
        }
        return newHead.next;
    }

②:

public ListNode deleteDuplicates(ListNode head) {
        if (head == null)
            return null;

        if (head.next != null && head.val == head.next.val) {
            while (head.next != null && head.val == head.next.val) {
                head = head.next;
            }
            return deleteDuplicates(head.next);
        } else {
            head.next = deleteDuplicates(head.next);
        }
        return head;
    }

 

 
 
 

 

相關文章