移除链表中的重复元素:设置二个指针begin&&end,间距为1;如果begin与end对应的属性值相同,则删掉end对应的元素并后移一位;否则,同时后移一位;
/**
* 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 *begin=head;
ListNode *end=NULL;
if(head!=NULL)
end=head->next;
else
return head;
while(end!=NULL)
{
if(end->val==begin->val)
{
begin->next=end->next;
end=end->next;
}
else
{
begin=begin->next;
end=end->next;
}
}
return head;
}
};
本文介绍了一种从链表中删除所有重复元素的方法。通过使用两个指针,begin 和 end,来遍历链表,当发现重复元素时,直接删除 end 指向的节点并调整 begin 的 next 指针指向 end 的 next。该算法简单高效,适用于单链表的数据结构。

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



