Coding Test/LeetCode
[LeetCode] 19. Remove Nth Node From End of List c++
owls
2022. 12. 27. 13:58
728x90
- 문제
Given the head of a linked list, remove the nth node from the end of the list and return its head.
linked list에 뒤에서 n번째 노드를 제거하는 문제입니다.
- 문제 해결
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *fast = head, *slow = head;
while(n--){
fast = fast->next;
}
if(!fast->next){
return head->next;
}
while(fast->next){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};
728x90