题解 | #删除链表中重复的结点#
删除链表中重复的结点
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) {
if (pHead == nullptr || pHead->next == nullptr) {
return pHead;
}
ListNode* dummyHead = new ListNode(0);
dummyHead->next = pHead;
ListNode* pCur = dummyHead;
while (pCur->next != nullptr && pCur->next->next != nullptr) {
// 相邻节点值相同
if (pCur->next->val == pCur->next->next->val) {
int tmp = pCur->next->val;
// 将所有相同的跳过
while (pCur->next != nullptr && pCur->next->val == tmp) {
pCur->next = pCur->next->next;
}
} else {
pCur = pCur->next;
}
}
ListNode* res = dummyHead->next;
delete dummyHead;
return res;
}
};
2023 剑指-链表 文章被收录于专栏
2023 剑指-链表
