LinkedList - 82. Remove Duplicates from Sorted List II

时间:2022-07-25
本文章向大家介绍LinkedList - 82. Remove Duplicates from Sorted List II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

82. Remove Duplicates from Sorted List II

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

Example 1:

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

Example 2:

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

思路:

题目意思是移除所有重复过的节点,做法就是得要找到当前节点和下一个节点不相同的节点,然后把链表接上,跳过重复的节点。

代码:

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 dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode prv = dummy, cur = dummy.next;
        
        while (cur != null) {
            while(cur.next != null && cur.next.val == cur.val) cur = cur.next;
            
            if (prv.next == cur) {
                prv = prv.next;
            } else {
                prv.next = cur.next; // 因为cur代表的是当前节点和下一个节点不相同所以cur有可能是重复元素 
            }
            
            cur = cur.next;
        }
        
        return dummy.next;
    }
}