Remove Duplicates from Sorted List II(删除排序链表中的重复数字 II)

问题

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

Have you met this question in a real interview? Yes
Example
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

代码

/**
 * 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
        //构造一个节点,可以完美解决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;
                //可以删除这两个节点了。
                head.next = head.next.next.next;
                while (head.next != null && head.next.val == val) {
                    //   如果后边还有相等,继续删除。
                    head.next = head.next.next;
                }
            } else {
                //不相等就向后遍历
                head = head.next;
            }
        }
        return dummy.next;
    }
}

你可能感兴趣的:(Remove Duplicates from Sorted List II(删除排序链表中的重复数字 II))