✉️문제
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
Remove Nth Node From End of List - LeetCode
Can you solve this real interview question? Remove Nth Node From End of List - Given the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: [https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg]
leetcode.com
📝 접근
O(n)에 푸는 것이 핵심이다. 이를 위해 투 포인터를 이용한다. 투 포인터의 간격은 n으로 설정한다.
🗝 문제풀이
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next == null) return null;
ListNode first = head;
ListNode second = head;
for(int i = 0; i < n; i++) {
second = second.next;
}
if(second == null) return first.next;
while(second.next != null) {
first = first.next;
second = second.next;
}
first.next = first.next.next;
return head;
}
}