当前位置:网站首页>删除有序链表中重复的元素-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;
}
};
边栏推荐
- Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
- 2022中国3D视觉企业(引导定位、分拣场景)厂商名单
- Arduino开发之按键检测与正弦信号输出
- 研发一款国产ARM智能边缘计算网关需要什么
- leetcode-934:最短的桥
- 【AutoSAR 八 OS】
- Shell implements basic file operations (SED edit, awk match)
- Vulkan performance and refinement
- RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
- Is there a free text to speech tool to help recommend?
猜你喜欢
Win10 多种方式解决无法安装.Net3.5的问题
基于ARM RK3568的红外热成像体温检测系统
Hdu3507 (slope DP entry)
【AutoSAR 十一 通信相关机制】
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
[AUTOSAR eight OS]
【案例分享】让新时代教育发展与“数”俱进
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
Advanced pointer (I)
leetcode-2280:表示一个折线图的最少线段数
随机推荐
解决ReactNative使用webView存在缓存问题
测试右移:线上质量监控 ELK 实战
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
【AutoSAR 十一 通信相关机制】
Rust string slicing, structs, and enumeration classes
Array common operation methods sorting (including ES6) and detailed use
[shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
Key detection and sinusoidal signal output developed by Arduino
The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
leetcode-871:最低加油次数
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
File operation io-part2
Arduino开发之按键检测与正弦信号输出
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
Meaning of Tencent cloud free SSL certificate extension file
In the first half of 2022, there are 10 worth seeing, and each sentence can bring you strength!
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
2022中国3D视觉企业(引导定位、分拣场景)厂商名单
【AutoSAR 二 AppL概述】
Solve the cache problem of reactnative using WebView