LeetCode83. Remove Duplicates from Sorted List

83.Remove Duplicates from Sorted List

題意: 給一個已排序的鏈表,刪除重複的元素,使得所有元素只出現一次。
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

想法: 一開始想的用 i、j 分別指向鏈表的前後元素,就像LeetCode26:移除數組中的重複元素一樣,結果這種方法是不對的,因爲鏈表本身自帶指針,用一個就可以,而且最後返回的還是head。

public class DeleteDuplicates_83 {
    class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
    }

    public ListNode deleteDuplicates(ListNode head) {       
         ListNode i = head;     
         while(i.next != null && i != null){                        
             if(i.val == i.next.val){                   
                 i.next = i.next.next;                      
             }
             else{
                 i = i.next;
             }
         }
         return head;       
    }
    //方法2 遞歸
    public ListNode deleteDuplicates1(ListNode head) {
        if(head == null || head.next == null)return head;
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
    }
}
發佈了48 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章