generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem5.cs
More file actions
46 lines (38 loc) · 1.16 KB
/
Problem5.cs
File metadata and controls
46 lines (38 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">Remove Nth Node From End of List</see>.
/// </summary>
public static class Problem5
{
/// <summary>
/// Given the head of a linked list, remove the nth node from the end of the list and return its head.
/// Time complexity: O(n).
/// Space complexity: O(1).
/// </summary>
/// <param name="head">Linked list head.</param>
/// <param name="n">Nth node to remove.</param>
/// <returns>New linked list head.</returns>
public static ListNode? RemoveNthFromEnd(ListNode head, int n)
{
var (count, next) = (1, head.Next);
while (next != null)
{
(count, next) = (count + 1, next.Next);
}
if (count < n)
{
return null;
}
var (previous, current) = (default(ListNode), head);
for (var i = count - n; i > 0; i--)
{
(previous, current) = (current, current!.Next);
}
if (previous == null)
{
return current!.Next;
}
previous.Next = current!.Next;
return head;
}
}