Programing/Algorithm
[LeetCode] 19. Remove Nth Node From End of List
Napoliano
2025. 2. 10. 11:31
728x90
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
public class Solution
{
public ListNode RemoveNthFromEnd(ListNode head, int n)
{
int nodeCount = 0;
var current = head;
while (current != null)
{
++nodeCount;
current = current.next;
}
if (nodeCount - n == 0)
return head.next;
current = head;
for (int i = 0; i < nodeCount - n - 1; i++)
current = current.next;
current.next = current.next.next;
return head;
}
}
public class Solution
{
public ListNode RemoveNthFromEnd(ListNode head, int n)
{
var dummy = new ListNode(0, head);
var fast = dummy;
var slow = dummy;
for (int i = 0; i < n; i++)
{
fast = fast.next;
}
while (fast.next != null)
{
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
728x90