Remove Nth Node From End of List - LeetCode
리스트가 주어질 때, 뒤에서 n 번째에 해당하는 노드를 삭제 하라.
먼저 뒤에서 n 번째의 노드를 찾는다.
slow, fast 포인터를 이용하면 찾을 수 있다.
이 후, head 처리에 유의하며 해당 노드를 삭제 한다.
더보기
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = nullptr;
int cnt = 0;
while (fast != nullptr)
{
if (cnt >= n)
{
prev = slow;
slow = slow->next;
}
fast = fast->next;
++cnt;
}
if(prev != nullptr)
prev->next = slow==nullptr ? nullptr : slow->next;
else
head = head->next;
return head;
}
결과
'Leetcode > NeetCode' 카테고리의 다른 글
[LinkedList][Medium] 2. Add Two Numbers. (0) | 2024.07.16 |
---|---|
[LinkedList][Medium] 138. Copy List with Random Pointer (0) | 2024.07.16 |
[LinkedList][Medium] 143. Reorder List (0) | 2024.07.15 |
[LinkedList][Easy] 21. Merge Two Sorted Lists (0) | 2024.07.15 |
[LinkedList][Easy] 206. Reverse Linked List. (0) | 2024.07.13 |