题目:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
解法 1
和 26 题很像,使用类似的双指针法。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* s = head;
ListNode* f = head->next;
while (f != nullptr) {
if (s->val == f->val) {
ListNode* tmp = f->next;
s->next = tmp;
delete f;
f = tmp;
} else {
s = f;
f = f->next;
}
}
return head;
}
};
解法 2
因为是排过序的,一个指针就阔以了。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr) { return head; }
ListNode* cur = head;
while (cur->next != nullptr) {
if (cur->val == cur->next->val) {
ListNode* tmp = cur->next;
cur->next = tmp->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};
EOF