题解 | #删除链表中重复的结点# 经典链表思路操作
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
// 创建一个虚拟头节点,方便操作,虚拟头结点的初始值需要时原链表中不包含的,否则影响重复性。
auto *v_head = new ListNode(0);
v_head -> next = pHead;
// 创建一个变量,存储要删除的值
int tar = -1;
ListNode *cur = pHead, *pre = v_head;
while(cur != nullptr){
if(cur->val != tar){
// 此处进行tar的更新
tar = cur -> val;
// 此处需要先判断cur->next是否为空
if(cur->next != nullptr && tar == cur->next->val){
// 进行针对tar的值的删除操作,/此处需要先判断cur是否为空
while(cur != nullptr && tar == cur->val){
ListNode *dele = cur;
cur = cur -> next;
pre -> next = cur;
delete dele;
}
}else{
// 此处进行tar不是重复值的指针更新操作
pre = cur;
cur = cur -> next;
}
}
}
ListNode* res = v_head->next;
delete v_head;
return res;
}
};
本题的逻辑思路比较经典,其中的虚拟头结点和pre、cur指针的思路都是清晰的,就是要注意在写具体代码的时候要特别注意空指针的检查,否则程序运行时一定会报错!
爱玛科技公司福利 6人发布