第56题 删除链表中重复的结点
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
auto vhead = new ListNode(-1);
vhead->next = pHead;
auto pre = vhead,cur = pHead;
while(cur){
if(cur->next && cur->next->val == cur->val){
while(cur->next && cur->next->val == cur->val){
cur = cur->next;
}
cur = cur->next;
pre->next = cur;
}else{
pre = cur;
cur = cur->next;
}
}
return vhead->next;
}
};
此篇博客介绍了一个算法问题,即如何删除排序链表中的重复节点,使得链表中每个节点的值都是唯一的。给出的解决方案是通过迭代,比较当前节点与其下一个节点的值,若相等则跳过重复部分,最终返回处理后的链表头指针。
172万+

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



