83. Remove Duplicates from Sorted List
方法1:
易错点:
- 需要guard against null的情况太多了
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return head;
ListNode* prev = head, *current = head;
while (true){
while (current && current -> val == prev -> val){
current = current -> next;
}
prev -> next = current;
prev = current;
if (!current) break;
current = current -> next;
}
return head;
}
};
更简洁的写法:
current保持不动,每次往前删掉一个相同的数字,当遇到不同的时候再交接current
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return head;
ListNode* prev = head, *current = head;
while (current && current -> next){
if (current -> val == current -> next -> val) {
current -> next = current -> next -> next;
}
else {
current = current -> next;
}
}
return head;
}
};
方法2: recursion
思路:
每次递归调用子节点,assuming子链已经无重复,再检查当前head和 head->next有没有重复。删除重复后返回当前head。
易错点:
要先递归再处理当前head和head->next,反过来会导致跳过一些重复无法删除
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) return head;
head -> next = deleteDuplicates(head -> next);
if ( head->val == head->next->val){
head -> next = head -> next -> next;
}
return head;
}
};