From a6d660cf0fa15d7f47c7f5ce9686d0bcac05366c Mon Sep 17 00:00:00 2001 From: fkdl0048 Date: Mon, 30 Sep 2024 14:57:08 +0900 Subject: [PATCH] Solve: Remove Nth Node From End of List --- .../Remove Nth Node From End of List.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 2024/LeetCode/Remove Nth Node From End of List.cpp diff --git a/2024/LeetCode/Remove Nth Node From End of List.cpp b/2024/LeetCode/Remove Nth Node From End of List.cpp new file mode 100644 index 0000000..e79ec96 --- /dev/null +++ b/2024/LeetCode/Remove Nth Node From End of List.cpp @@ -0,0 +1,30 @@ +/** + * 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* res = new ListNode(0, head); // 반환할 복사본 생성 + ListNode* dummy = res; + + for (int i = 0; i < n; i++){ + head = head->next; + } + + while (head != nullptr){ + head = head->next; + dummy = dummy->next; + } + + dummy->next = dummy->next->next; + + return res->next; + } +}; \ No newline at end of file