hahn

[LeetCode - C] 83. Remove Duplicates from Sorted List 본문

코딩테스트 연습/LeetCode(C - Easy)

[LeetCode - C] 83. Remove Duplicates from Sorted List

hahn 2022. 4. 18. 05:31
728x90
반응형
 

Remove Duplicates from Sorted List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

Solution 1

 

linked list 다루는 문제다.

 

현재 노드와 다른 값을 가진 노드를 찾은 뒤 이어주면 된다. 

 

malloc된 노드면 free 해줘야 하나 그런 말 없어서 그냥 진행했다.

 

null일 때 예외 처리했다.

struct ListNode* deleteDuplicates(struct ListNode* head)
{
    struct ListNode *next_node;
    struct ListNode *current_node;
    
    if (!head)
        return (head);
    current_node = head;
    next_node = current_node -> next;
    while (current_node -> next)
    {
        while (next_node && next_node -> val == current_node -> val)
            next_node = next_node -> next;
        current_node -> next = next_node;
        current_node = current_node -> next;
        if (!current_node)
            break;
        next_node = current_node -> next;
    }
    return (head);
}

Solution 2

 

좀 더 깔끔한 ver

struct ListNode* deleteDuplicates(struct ListNode* head)
{
    struct ListNode *current_node;
    
    current_node = head;
    while (current_node && current_node -> next)
    {
        if (current_node -> val == current_node -> next -> val)
            current_node -> next = current_node -> next -> next;
        else
            current_node = current_node -> next;
    }
    return (head);
}
728x90
반응형