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;
    }
};
相关推荐
To_OC2 小时前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
闪电悠米14 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
过期动态17 小时前
【LeetCode 热题 100】找到字符串中所有字母异位词
java·数据结构·算法·leetcode·职场和发展·rabbitmq
Adios7941 天前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅1 天前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
hold?fish:palm2 天前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle2 天前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木2 天前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz2 天前
算法:回溯算法
c++·算法·leetcode
小肝一下2 天前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra