83.删除有序链表中的重复元素 (Easy)*
题目描述*
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例*
输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3
代码*
逐个判断即可,迭代或递归。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
ListNode *cur = head;
while(cur->next != nullptr) {
if(cur->next->val == cur->val) {
cur->next = cur->next->next;
}else {
cur = cur->next;
}
}
return head;
}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
head->next = deleteDuplicates(head->next);
return head->val == head->next->val ? head->next : head;
}
};
执行用时:16ms
内存消耗:9.2MB
最后更新: July 23, 2022