https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints:
- The number of nodes in the list is in the range [0, 300].
- -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
1.C
기본적인건데도 왜이렇게 짜치냐
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(!head||!head->next) return head;
struct ListNode* slow = head;
struct ListNode* fast = head;
while(fast){
while(fast->next && fast->val == fast->next->val){
fast = fast->next;
}
if(slow->val==fast->val) fast=fast->next;
slow->next = fast;
slow = fast;
if(!fast) break;
fast = fast->next;
}
return head;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(!head || !head->next) return head;
struct ListNode* curr = head;
while(curr && curr->next){
if(curr->val == curr->next->val){
curr->next = curr->next->next;}
else curr = curr->next;
}
return head;
}
위와 같이 어찌보면 간단히 할 수 있는 건데;; 에효 좀 헷갈렸다.
2. C++
비슷한 결로 해결. 중복 delete로 제거까지 포함했다.
/**
* 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) {
if(!head || !head->next) return head;
ListNode* curr = head;
while(curr && curr->next){
if(curr->val == curr->next->val){
ListNode* temp = curr->next;
curr->next = curr->next->next;
delete temp;
}
else curr = curr->next;
}
return head;
}
};
3. Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next :
return head
curr = head
while curr and curr.next:
if curr.val == curr.next.val :
curr.next = curr.next.next
else :
curr = curr.next
return head
하나 느낀 건, while문을 난발하다보면 코드가 꼬인다는 것이다.
코딩하면서 제일 무서운 while / recursive 구조 ㅠㅠ 언제 친해지냐
'Coding_Practice' 카테고리의 다른 글
Swap Nodes in Pairs[M,Linked List,Recursion] (0) | 2024.08.16 |
---|---|
Maximum Distance in Arrays[M,Array,Greedy] (0) | 2024.08.16 |
Find K-th Smallest Pair Distance[H,Array,Two Pointers,Binary Search,Sorting] (0) | 2024.08.14 |
Combination Sum II[M,Array,Backtracking] (0) | 2024.08.13 |
Median of Two Sorted Arrays[H,Array,Binary Search,Divide and Conquer] (0) | 2024.08.12 |