题解 | #删除链表中重复的结点#
删除链表中重复的结点
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) {
return nullptr;
}
ListNode* ans = new ListNode(0);
ans->next = pHead;
ListNode* cur = ans;
while (cur->next != NULL && cur->next->next != NULL) {
if (cur->next->val == cur->next->next->val) {
int temp = cur->next->val;
//使用 while 循环遍历链表,检查当前节点的下一个和下下个节点是否存在,确保后续访问不会越界。
while (cur->next != NULL && cur->next->val == temp) {
cur->next = cur->next->next;
}
}
else
cur = cur->next;
}
return ans->next;
}
};
本来想的是用两个指针,但是实际上用一个还比较方便,还是要深刻认识ans->next 和ans->next->next,以及代码中关键的用一个while循环来删除重复的数字
