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;
    }
};
相关推荐
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll4 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐4 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶4 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER4 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了4 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333335 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录5 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1235 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode