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;
    }
};
相关推荐
啊嘞嘞?12 小时前
力扣(回文链表)
算法·leetcode·链表
淡海水13 小时前
03-05-线性-Array-List-LinkedList与Span-所有权与成本模型选型
c#·list·编译·array·clr·机器码
wabs66613 小时前
关于栈【力扣150.逆波兰表达式求值的思考】
数据结构·c++·算法·leetcode··代码随想录
牛油果子哥q13 小时前
C++序列式容器深度精讲:vector/list/deque底层实现、扩容原理、迭代器失效、性能对比、工程选型避坑
开发语言·c++·list
Navigator_Z1 天前
LeetCode //C - 1206. Design Skiplist
c语言·算法·leetcode
码行山野赴时序归途1 天前
三道经典数组题:从暴力到最优的算法思维
c语言·开发语言·数据结构·算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1209. Remove All Adjacent Duplicates in String II
c语言·算法·leetcode
土司大王1 天前
LeetCode hot100——合并两个有序链表
算法·leetcode·链表
wabs6661 天前
关于栈【力扣1047. 删除字符串中的所有相邻重复项的思考】
数据结构·c++·算法·leetcode··代码随想录
evans在进步2 天前
LeetCode 53 最大子数组和:一次遍历掌握 Kadane 算法
算法·leetcode·职场和发展