Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List II


今天是一道有關鏈表的題目,來自LeetCode,難度為Medium,Acceptance為27%

題目如下


Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

解題思路及代碼見閱讀原文

回復0000查看更多題目

解題思路


首先,該題是Remove Duplicates from Sorted List 的升級版,難度略有加大,但是其實也并不難。區別是,在Remove Duplicates from Sorted List一題中,是對重復的數字只保留一個,這里是一個都不保留。

然后,了解是上述區別,應該如何改變算法呢:

  • 在Remove Duplicates from Sorted List一題中我們這樣做,用一個指針遍歷整個鏈表,如果要保留一個數字,則用這個指針指向的節點和已經加入結果列表的尾節點比較,如果相同則跳過;

  • 在本題中我們不保留重復的節點,那么我們可以用如下方法:

1.首先用一個循環跳過相同的節點;

2.用該節點和已經加入鏈表的尾節點的下一個節點比較,如果相同則加入鏈表;

3.如果不同,則跳過該節點。

好了,有了上述思路,下面我們來看代碼。

代碼如下


Java版

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param ListNode head is the head of the linked list
     * @return: ListNode head of the linked list
     */
    public static ListNode deleteDuplicates(ListNode head) {
        // write your code here
        if(null == head)
            return null;
        ListNode newHead = new ListNode(0), p = newHead, fast = head;
        newHead.next = head;
        while(fast != null) {
           while(fast.next != null && fast.val == fast.next.val) {
               fast = fast.next;
           }
           if(p.next == fast) {
               p = p.next;
           } else {
               p.next = fast.next;
           }
           fast = fast.next;
        }
        p.next = null;
        return newHead.next;
    }
}

關注我
該公眾號會每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學有所幫助

image
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容