LeetCode 82. Remove Duplicates from Sorted List II
原题链接在这里:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
题解:
类似Remove Duplicates from Sorted List, 不同就是要完全去掉duplicate.
当cur.next.val == cur.next.next.val 时,就一直移动dup = cur.next.next直到cur.next.val != dup.val. 然后cur的next指向dup.
Time Complexity: O(n), n 是list长度.
Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode deleteDuplicates(ListNode head) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 15 ListNode dummy = new ListNode(0); 16 dummy.next = head; 17 ListNode cur = dummy; 18 while(cur.next != null && cur.next.next != null){ 19 if(cur.next.val != cur.next.next.val){ 20 cur = cur.next; 21 }else{ 22 ListNode dup = cur.next.next; 23 while(dup != null && cur.next.val == dup.val){ 24 dup = dup.next; 25 } 26 cur.next = dup; 27 } 28 } 29 30 return dummy.next; 31 } 32 }
AC C++:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* deleteDuplicates(ListNode* head) { 14 if(!head || !head->next){ 15 return head; 16 } 17 18 ListNode* dummy = new ListNode(-1, head); 19 ListNode* it = dummy; 20 while(it->next && it->next->next){ 21 if(it->next->val != it->next->next->val){ 22 it = it->next; 23 }else{ 24 ListNode* dup = it->next->next; 25 while(dup && dup->val == it->next->next->val){ 26 dup = dup->next; 27 } 28 29 it->next = dup; 30 } 31 } 32 33 return dummy->next; 34 } 35 };
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 通过抓包,深入揭秘MCP协议底层通信
· 记一次.NET MAUI项目中绑定Android库实现硬件控制的开发经历
· 糊涂啊!这个需求居然没想到用时间轮来解决
· 浅谈为什么我讨厌分布式事务
· 在 .NET 中使用内存映射文件构建高性能的进程间通信队列
· 那些年我们一起追过的Java技术,现在真的别再追了!
· 还在手写JSON调教大模型?.NET 9有新玩法
· 为大模型 MCP Code Interpreter 而生:C# Runner 开源发布
· 面试时该如何做好自我介绍呢?附带介绍样板示例!!!
· JavaScript 编年史:探索前端界巨变的幕后推手