1. 题目
存在一个按升序排列的链表,给你这个链表的头节点 head
,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
2. 分析
- 递归:
- 找终止条件:当head指向链表只剩一个元素的时候,自然是不可能重复的,因此return;
- 想想应该返回什么值:应该返回的自然是已经去重的链表的头节点;
- 每一步要做什么:宏观上考虑,此时head.next已经指向一个去重的链表了,而根据第二步,我应该返回一个去重的链表的头节点。因此这一步应该做的是判断当前的head和head.next是否相等,如果相等则说明重了,返回head.next,否则返回head
- 迭代:若当前节点值与下一节点值相同,则cur -> next = cur -> next -> next; 若不相同,则cur = cur -> next;
代码如下:
// 递归
ListNode* deleteDuplicates(ListNode* head) {
if(head == nullptr || head -> next == nullptr)
return head;
head -> next = deleteDuplicates(head -> next);
if(head -> next -> val == head -> val) head = head -> next;
return head;
}
// 迭代
ListNode* deleteDuplicates(ListNode* head) {
if(!head) return nullptr;
ListNode* cur = head;
while(cur -> next){
if(cur -> val == cur -> next -> val)
cur -> next = cur -> next -> next;
else
cur = cur -> next;
}
return head;
}