[leetcode] 82. Remove Duplicates from Sorted List II

网友投稿 545 2022-10-01

[leetcode] 82. Remove Duplicates from Sorted List II

[leetcode] 82. Remove Duplicates from Sorted List II

Description

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input:

1->2->3->3->4->4->5

Output:

1->2->5

Example 2:

Input:

1->1->1->2->3

Output:

2->3

分析

题目的意思是:给定一个链表,移除重复的节点。

类似于快慢指针,快指针寻找重复的结点,慢指针指向未重复链表的末尾

代码

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* deleteDuplicates(ListNode* head) { ListNode* dummy=new ListNode(-1); dummy->next=head; ListNode* slow=dummy; ListNode* fast=head; while(fast){ while(fast->next&&fast->val==fast->next->val){ fast=fast->next; } if(slow->next!=fast){ slow->next=fast->next; fast=slow->next; }else{ slow=slow->next; fast=fast->next; } } return dummy->next; }};

参考文献

​​[编程题]remove-duplicates-from-sorted-list-ii​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信公众号一个月只能发4次消息怎么办?
下一篇:[leetcode] 27. Remove Element
相关文章

 发表评论

暂时没有评论,来抢沙发吧~