vault backup: 2022-06-16 14:32:37
This commit is contained in:
parent
4a5488aa8c
commit
026953d9bd
|
@ -0,0 +1,71 @@
|
|||
# Leetcode Remove-Duplicates-From-Sorted-List
|
||||
|
||||
#### 2022-06-16 14:21
|
||||
|
||||
> ##### Data structures:
|
||||
> #DS #linked_list
|
||||
> ##### Difficulty:
|
||||
> #coding_problem #difficulty-easy
|
||||
> ##### Additional tags:
|
||||
> #leetcode
|
||||
> ##### Revisions:
|
||||
> Initial encounter: 2022-06-16
|
||||
|
||||
##### Related topics:
|
||||
```expander
|
||||
tag:#linked_list
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Links:
|
||||
- [Link to problem]()
|
||||
___
|
||||
### Problem
|
||||
|
||||
#### Examples
|
||||
|
||||
#### Constraints
|
||||
|
||||
### Thoughts
|
||||
|
||||
This can be implemented using recursion and iteration, like [[Leetcode Reverse-Linked-List]].
|
||||
Recursion is not recommended, since it will take up O(n) space.
|
||||
In iteration, one pointer or 2 pointers can be used.
|
||||
|
||||
To understand the ptr->next->next = ptr->next, see[[Leetcode Reverse-Linked-List#Solution]]
|
||||
|
||||
### Solution
|
||||
|
||||
One pointer method
|
||||
```cpp
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* struct ListNode {
|
||||
* int val;
|
||||
* ListNode *next;
|
||||
* ListNode() : val(0), next(nullptr) {}
|
||||
* ListNode(int x) : val(x), next(nullptr) {}
|
||||
* ListNode(int x, ListNode *next) : val(x), next(next) {}
|
||||
* };
|
||||
*/
|
||||
class Solution {
|
||||
public:
|
||||
ListNode *deleteDuplicates(ListNode *head) {
|
||||
ListNode *ptr = head;
|
||||
while (ptr != NULL && ptr->next != NULL) {
|
||||
if (ptr->val == ptr->next->val) {
|
||||
// Duplicate found
|
||||
auto tmp = ptr->next;
|
||||
ptr->next = ptr->next->next;
|
||||
delete tmp;
|
||||
// I done set ptr to ptr->next, in case new ptr->next is duplicated
|
||||
} else {
|
||||
ptr = ptr->next;
|
||||
}
|
||||
}
|
||||
return head;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
Loading…
Reference in a new issue