文章 224
评论 6
浏览 200774
LinkedList - 82. Remove Duplicates from Sorted List II

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;
    }
}

标题:LinkedList - 82. Remove Duplicates from Sorted List II
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/07/28/1564324550161.html

Nothing just happens, it's all part of a plan.

取消