当前位置:网站首页>删除有序链表中重复的元素-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;
}
};
边栏推荐
- [daily training] 871 Minimum refueling times
- Array common operation methods sorting (including ES6) and detailed use
- What is needed to develop a domestic arm intelligent edge computing gateway
- File operation io-part2
- 飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
- Leetcode-871: minimum refueling times
- [AUTOSAR VI description document]
- Win10 can't be installed in many ways Problems with NET3.5
- leetcode-934:最短的桥
- Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
猜你喜欢

How to convert Quanzhi a40i/t3 to can through SPI

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

Advanced pointer (I)

瑞萨RZ/G2L ARM开发板存储读写速度与网络实测

Detailed explanation of pod life cycle

Attributeerror: 'tuple' object has no attribute 'layer' problem solving

Linux软件:如何安装Redis服务

数据分析思维分析犯法和业务知识——分析方法(一)
![[AUTOSAR I overview]](/img/e4/b97c6beebf6f431d2d7cf209c6683e.png)
[AUTOSAR I overview]

如何系统学习机器学习
随机推荐
[AUTOSAR XIII NVM]
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
leetcode-241:为运算表达式设计优先级
RK3568开发板评测篇(二):开发环境搭建
Reading and writing speed of Reza rz/g2l arm development board storage and network measurement
研发一款国产ARM智能边缘计算网关需要什么
[AUTOSAR twelve mode management]
关于XML一些介绍和注意事项
图解网络:什么是虚拟路由器冗余协议 VRRP?
1.12 - Instructions
leetcode-2280:表示一个折线图的最少线段数
[love crash] neglected details of gibaro
Leetcode-871: minimum refueling times
瑞萨电子RZ/G2L开发板上手评测
RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
lex && yacc && bison && flex 配置的问题
解决ReactNative使用webView存在缓存问题
【AutoSAR 十一 通信相关机制】
matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决
[shutter] image component (the placeholder | transparent_image transparent image plug-in is loaded into the memory)