mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 82. Remove Duplicates from Sorted List II.md
This commit is contained in:
parent
5e2fccf506
commit
623fa57ae2
54
solutions/82. Remove Duplicates from Sorted List II.md
Normal file
54
solutions/82. Remove Duplicates from Sorted List II.md
Normal file
@ -0,0 +1,54 @@
|
||||
# [82. Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)
|
||||
|
||||
# 思路
|
||||
删除一个有序链表中出现次数超过一次的元素。
|
||||
## 思路一
|
||||
为了方便处理我们先增加一个头结点real_head,并令指针p指向已经处理好的链表的最后一个元素,初始为real_head;令指针p为遍历工作指针。
|
||||
我们这样向后移动p指针:若p后面的节点元素值等于p指向的元素,则p指针后移,直到p后面的节点元素值不等于p指向的元素。此时有两种情况:
|
||||
* 如果 `p -> next == q`,则p指向的元素没有重复,要保留,则令 `p = q`,然后q向后移动一步进入下一循环。
|
||||
* 否则,说明p指向的元素出现次数超过了一次,那么应该跳过这些元素,即`p -> next = q -> next`, 然后q向后移动一步进入下一循环。
|
||||
|
||||
最后返回的是`real_head -> next`。
|
||||
|
||||
## 思路二、递归
|
||||
我们也可以使用递归来做,首先判空,如果head为空,直接返回。然后按照和思路一同样的规则移动工作指针p,判断p和head的关系:
|
||||
* 若`p == head`说明此元素可以保留,则将`head -> next`指向`deleteDuplicates(head -> next)`,再返回head;
|
||||
* 否则,说明p指向的元素出现次数超过了一次,那么应该跳过这些元素,则直接返回`deleteDuplicates(p -> next)`。
|
||||
|
||||
# C++
|
||||
## 思路一
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
ListNode* deleteDuplicates(ListNode* head) {
|
||||
ListNode *real_head = new ListNode(0);
|
||||
real_head -> next = head;
|
||||
ListNode *p = real_head, *q = head;
|
||||
while(q){
|
||||
while(q -> next && q -> next -> val == q -> val) q = q -> next;
|
||||
if(p -> next == q) p = q;
|
||||
else p -> next = q -> next;
|
||||
|
||||
q = q -> next;
|
||||
}
|
||||
return real_head -> next;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## 思路二
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
ListNode* deleteDuplicates(ListNode* head) {
|
||||
if(head == NULL) return head;
|
||||
ListNode *p = head;
|
||||
while(p -> next && p -> val == p -> next -> val) p = p -> next;
|
||||
if(p == head){
|
||||
head -> next = deleteDuplicates(head -> next);
|
||||
return head;
|
||||
}
|
||||
else return deleteDuplicates(p -> next);
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user