자료구조 알고리즘/코딩테스트

Remove Nth Node From End of List

내공얌냠 2021. 7. 3. 16:26

19. Remove Nth Node From End of List

난이도: Easy

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

 

Remove Nth Node From End of 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

 

Language: C++

/**
 * 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* removeNthFromEnd(ListNode* head, int n) {
        ListNode* node = head;
        int length = 0;
        while (node) {
            length++;
            node = node->next;
        }
        
        length = length - n;
        if (length < 0)
            return NULL;
        else {
            node = head;
            while (length > 1) {
                node = node->next;
                length--;
            }
            if (length == 0)
                head = head->next;
            else
                node->next = node->next->next;
            
        }
        
        return head;
        
    }
};

 

야호

아마도 지금 푼 것 중에서 처음으로 내가 혼자 다 풀었다.. (난이도 Easy...)

솔루션은 dummy라고 dummy.next = head 를 넣어서 while (length > 0) 하고, node->next = node->next->next; 만 쓰도록 하여 간소화 시켰다.

728x90
반응형