Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
- 重复的node要删得一个都不剩
- 因为重复可能从head就开始,相当于head有可能会被删除,此时需要构造dummy node在头部,以便利head的删除。
- prev还是指向删除前的node,crt一直while到重复node的后面,然后一次性删除重复node
- 涉及到需要读crt->next->val的时候,一定要考虑到排除了crt->next为NULL的可能性,不然报错。
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: head is the head of the linked list
* @return: head of the linked list
*/
ListNode * deleteDuplicates(ListNode * head) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *prev = dummy;
ListNode *crt = head;
while (crt != NULL && crt->next != NULL) {
if (crt->val != crt->next->val) {
prev = crt;
crt = crt->next;
} else {
while (crt->next != NULL && crt->val == crt->next->val) {
crt = crt->next;
}
prev->next = crt->next;
crt = crt->next;
}
}
return dummy->next;
}
};