Leetcode 82. Remove Duplicates from Sorted List II

  1. Remove Duplicates from Sorted List II
    Medium
    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.

Example 1:

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

Output: [1,2,5]

Example 2:

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.

解法1:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return NULL;
        ListNode* dummy = new ListNode(0), *p1 = dummy, *p2 = head;
        dummy->next = head;
        while (p2 && p2->next) {
            if (p2->val == p2->next->val) {
                while (p2 && p2->next && p2->val == p2->next->val) {
                    p2 = p2->next;
                }
                p1->next = p2->next;
            } else {
                p1 = p1->next;    
            }
            p2 = p2->next;
        }
        return dummy->next;
    }
};
相关推荐
灋✘逞_兇33 分钟前
快速幂+公共父节点
数据结构·c++·算法·leetcode
飞川撸码3 小时前
【LeetCode 热题100】二叉树构造题精讲:前序 + 中序建树 & 有序数组构造 BST(力扣105 / 108)(Go语言版)
数据结构·leetcode·golang·二叉树
雾里看山3 小时前
算法思想之位运算(一)
算法·leetcode·推荐算法
描绘一抹色5 小时前
力扣-hot100(最长连续序列 - Hash)
数据结构·算法·leetcode
学习2年半8 小时前
回溯算法:List 还是 ArrayList?一个深拷贝引发的思考
数据结构·算法·list
Wils0nEdwards11 小时前
Leetcode 独一无二的出现次数
算法·leetcode·职场和发展
Y.O.U..11 小时前
力扣HOT100——无重复字符的最长子字符串
数据结构·c++·算法·leetcode
Ludicrouers13 小时前
【Leetcode-Hot100】和为k的子数组
算法·leetcode·职场和发展
purrrew19 小时前
【数据结构_5】链表(模拟实现以及leetcode上链表相关的题目)
数据结构·leetcode·链表
梭七y20 小时前
【力扣hot100题】(097)颜色分类
算法·leetcode·职场和发展