Given a sorted linked list, delete all duplicates such that each element appear only once.
- 删除重复node,重复值node保留一个。
- 两个指针,prev,crt(分别指向前一个node,当前node)
- 当遇到crt和prev相等时,crt不断往后找到不相等的那个位置,然后一次性删掉中间重复的node
/**
* 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 linked list
*/
ListNode * deleteDuplicates(ListNode * head) {
if(head == NULL) {
return head;
}
ListNode * prev = head;
ListNode * crt = head->next;
while (crt != NULL) {
if (crt->val == prev->val) {
while (crt->next != NULL && crt->val == crt->next->val) {
crt = crt->next;
}
crt = crt->next;
prev->next = crt;
} else {
prev = crt;
crt = crt->next;
}
}
return head;
}
};
/**
* 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 linked list
*/
ListNode * deleteDuplicates(ListNode * head) {
if (head == NULL) {
return head;
}
ListNode *prev = head;
ListNode *crt = head->next;
while (crt != NULL) {
if (crt->val != prev->val) {
prev = crt;
crt = crt->next;
}
while (crt != NULL && crt->val == prev->val) {
crt = crt->next;
}
prev->next = crt;
}
return head;
}
};