(Java) LeetCode 83. Remove Duplicates from Sorted List —— 刪除排序鏈表中的重複元素

來源:互聯網
上載者:User

標籤:int   solution   節點   efi   ted   move   next   IV   amp   

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2Output: 1->2

Example 2:

Input: 1->1->2->3->3Output: 1->2->3

 

很簡單的鏈表問題,可以寫成遞迴和迭代兩種形式。具體思路:

第一步,尋找第一個節點值和當前表頭所指的節點值不同的節點;

第二步,讓當前表前端節點的next指向找到的節點;

第三部,遞迴調用前兩步,或迭代調用前兩步。

 

詳細代碼註解見下。

 

 

遞迴解法(Java)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode deleteDuplicates(ListNode head) {        if (head == null || head.next == null) return head; //特殊情況處理,即空鏈表和單節點鏈表直接返回        ListNode cur = head.next; //設定指標指向表頭後的第一個節點        while (cur != null && cur.val == head.val) cur = cur.next; //第一步,尋找第一個節點值和當前表前端節點所指節點值不同的節點        head.next = deleteDuplicates(cur); //找到後,進行第二步,即讓當前表前端節點的next指向剛才找到的節點。這裡用了遞迴調用,上面找到的不重複節點是cur,那麼這個遞迴返回的恰恰是cur,且同時執行以cur為節點頭的去重工作        return head; //返回頭結點    }}

 

迭代解法(Java)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode deleteDuplicates(ListNode head) {        if (head == null || head.next == null) return head; //特殊情況處理,同迭代解法        ListNode pre = head, cur = head.next; //定義兩個指標分別指向當前前端節點和其下一個節點        while (cur != null) {            if (cur.val == pre.val) cur = cur.next; //第一步,尋找第一個非重複節點            else {                 pre.next = cur; //找到後進行第二步,即讓當前節點pre的next指向找到的節點cur                pre = cur; //之後重複之前的過程                cur = pre.next;             }        }        pre.next = cur; //迭代到最後因為cur為null的時候就跳出迴圈了,沒有執行最後的去重,所以加一句讓鏈表末尾沒有重複節點        return head;    }}

 

(Java) LeetCode 83. Remove Duplicates from Sorted List —— 刪除排序鏈表中的重複元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.