当前位置:网站首页>删除有序链表中重复的元素-II
删除有序链表中重复的元素-II
2022-07-03 00:29:00 【Schuyler Hu】
问题
出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
思路
利用快慢双指针,fast 去探测非重复元素,slow 负责记录非重复元素。
代码实现
/** * struct ListNode { * int val; * struct ListNode *next; * }; */
class Solution {
public:
/** * * @param head ListNode类 * @return ListNode类 */
ListNode* deleteDuplicates(ListNode* head) {
// write code here
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* slow = dummyHead;
ListNode* fast = dummyHead->next;
while (fast && fast->next)
{
// 下一个节点 != 当前节点,当前节点不是重复元素
if (fast->next->val != fast->val)
{
// fast 探测到的不是重复节点,因此 slow 可以直接往前挪
slow = fast;
fast = fast->next;
}
else
{
// fast 探测到重复元素,记录重复元素,并向前挪
int repeatVal = fast->val;
// fast 不等于重复元素,退出循环,不能保证该节点不是重复节点
// 如:1 2 2 3 3,还要继续比较 fast 和下一个元素
while (fast && fast->val == repeatVal)
{
fast = fast->next;
}
slow->next = fast;
}
}
return dummyHead->next;
}
};
边栏推荐
- Infrared thermography temperature detection system based on arm rk3568
- 深度剖析数据在内存中的存储
- 1.11 - 总线
- Array common operation methods sorting (including ES6) and detailed use
- 关于QByteArray存储十六进制 与十六进制互转
- 如何系统学习机器学习
- 百度智能云牵头打造智能云综合标准化平台
- Basic use of sringcloud & use of component Nacos
- Leetcode-849: maximum distance to the nearest person
- Rust所有权(非常重要)
猜你喜欢

深度剖析数据在内存中的存储

世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力

Basic use of sringcloud & use of component Nacos

Rust ownership (very important)

Advanced pointer (I)
![[AUTOSAR II appl overview]](/img/da/76ccc05e2199705b20d8304bfb86b2.png)
[AUTOSAR II appl overview]

Hdu3507 (slope DP entry)

Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)

数据分析思维分析犯法和业务知识——分析方法(一)
![[AUTOSAR 11 communication related mechanism]](/img/bf/834b0fad3a3e5bd9c1be04ba150f98.png)
[AUTOSAR 11 communication related mechanism]
随机推荐
【AutoSAR 四 BSW概述】
leetcode-2115:从给定原材料中找到所有可以做出的菜
Illustrated network: what is virtual router redundancy protocol VRRP?
【案例分享】让新时代教育发展与“数”俱进
数组与集合性能比较
Test shift right: Elk practice of online quality monitoring
Arduino开发之按键检测与正弦信号输出
2022中国3D视觉企业(引导定位、分拣场景)厂商名单
【AutoSAR 十二 模式管理】
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
机器学习:numpy版本线性回归预测波士顿房价
1.12 - 指令
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
【AutoSAR 三 RTE概述】
Shell implements basic file operations (cutting, sorting, and de duplication)
tail -f 、tail -F、tailf的区别
leetcode-224:基本计算器
Leetcode-2280: represents the minimum number of line segments of a line graph