- 删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
思路一:直接删除法,注意删除节点的垃圾回收
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* pList = head;
while (pList && pList->next){
if (pList->val == pList->next->val){
ListNode* del = pList->next;
pList->next = pList->next->next;
delete del;
}else {
pList = pList->next;
}
}
return head;
}
};
时间复杂度: O(n),空间复杂度: O(1)
思路二:递归删除法(神奇的递归)
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL){
return head;
}
head->next = deleteDuplicates(head->next);
if (head->val == head->next->val){
//ListNode* del = head->next;
//head->next = head->next->next;
ListNode* del = head;
head = head->next;
delete del;
}
return head;
}
};
时间复杂度: O(n),空间复杂度: O(1)