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
'Programing > Algorithm' 카테고리의 다른 글
[LeetCode] 33. Search in Rotated Sorted Array (0) | 2025.02.12 |
---|---|
[LeetCode] 22. Generate Parentheses (0) | 2025.02.10 |
[LeetCode] 17. Letter Combinations of a Phone Number (0) | 2025.02.10 |
[LeetCode] 15. 3Sum (0) | 2025.02.10 |
[LeetCode] 11. Container With Most Water (0) | 2025.02.08 |