#82 Remove Duplicates from Sorted List II

Description

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

Examples

Example 1:
#82 Remove Duplicates from Sorted List II

Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2:
#82 Remove Duplicates from Sorted List II

Input: head = [1,1,1,2,3]
Output: [2,3]

Constraints:

The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.

Solution

  • 首先给整个链表加上一个额外的,这样可以不用分开来处理头部有相同数字串出现的情况,确保后续数据处理的统一性。

对于后面的数据(可能会比较绕)

  • 假设我们已经确认了一个单个的、会被保留的节点single(起始时为那个额外的头),对于这个single,用一个指针pointer指向它的next节点,去寻找后续节点中有没有和next.val相同的节点
    – 如果没有相同节点,让single指向pointer
    – 如果有相同节点,让singel不变,pointer指向下一个不同val的节点
  • 循环直到single为null

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) { 
        ListNode answer = new ListNode();
        int number;
        answer.next = head;
        ListNode father = answer;
        while(father.next != null){
            Boolean flag = false;
            ListNode current = father.next;
            number = current.val;
            current = current.next;
            while(current != null && current.val == number){
                flag = true;
                current = current.next;
            }
            if(flag){
                father.next = current;
                continue;
            }
            father = father.next;
        }
        return answer.next;
    }
}

其他

很奇怪的是它不支持 if(head)这种写法
必须得写成 if(head != null),不知道是什么问题
另:lc能告诉你错在哪个样例上真是太棒了QuQ

上一篇:26. Remove Duplicates from Sorted Array


下一篇:83. Remove Duplicates from Sorted List