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;
    }
};
相关推荐
圣保罗的大教堂1 小时前
leetcode 3418. 机器人可以获得的最大金币数 中等
leetcode
_日拱一卒5 小时前
LeetCode:最大子数组和
数据结构·算法·leetcode
小辉同志7 小时前
78. 子集
算法·leetcode·深度优先
Demon--hx10 小时前
[LeetCode]100 链表-专题
算法·leetcode·链表
_深海凉_11 小时前
LeetCode热题100-LRU 缓存
算法·leetcode·缓存
csdn2015_11 小时前
List<DocumentMetadata> 取所有docid,组成List<String>
windows·python·list
liuyao_xianhui12 小时前
优选算法_岛屿的最大面积_floodfill算法_C++
java·开发语言·数据结构·c++·算法·leetcode·链表
happymaker062612 小时前
vue中对list的函数处理方式总结,以及常见功能的实现方法
javascript·vue.js·list
We་ct13 小时前
LeetCode 190. 颠倒二进制位:两种解法详解
前端·算法·leetcode·typescript