Remove Duplicates from Sorted List II

Fair Remove Duplicates from Sorted List IIMy Submissions

28%
Accepted

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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.

KEY: 

1. use dummy node. Because the head of the original node might be changed.

2. every iteration we compare head.next.val with head.next.next.val. Save head.next.val if the the two adjacent nodes are equal. And use a while loop to delete all the nodes with the same value. The deletion starts from head.next.

</pre><pre name="code" class="java">
</pre><p></p><p><pre name="code" class="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) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        
        while (head.next != null && head.next.next != null) {
            if (head.next.val == head.next.next.val) {
                int val = head.next.val;
                while (head.next != null && head.next.val == val) {
                    head.next = head.next.next;
                }
            } else {
                head = head.next;
            }
        }
        return dummy.next;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章