/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*本题思路简单,直接用两个指针pre和cur,分别指向当前指针的
前一个结点和当前结点,如果两个值相同,则删除当前结点,遍历整个链表。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == nullptr) return head;
ListNode *pre = head, *cur = pre->next;
if(cur == nullptr) return head;
for(;cur != nullptr; cur = cur->next){
if(cur->val == pre->val){
pre->next = cur->next;
delete cur;
}
else{
pre = pre->next;
}
}
return head;
}
};LeetCode之Remove Duplicates from Sorted List
最新推荐文章于 2022-04-06 16:22:53 发布
本文介绍如何使用双指针技巧实现删除单链表中重复节点的功能,通过比较当前节点与下一个节点的值,若相等则删除当前节点。
710

被折叠的 条评论
为什么被折叠?



