-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19-Remove-Nth-Node-from-End-of-List.cs
More file actions
65 lines (56 loc) · 1.42 KB
/
Copy path19-Remove-Nth-Node-from-End-of-List.cs
File metadata and controls
65 lines (56 loc) · 1.42 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#region Two Pointers (1 pass)
// Time O(n)
// Space O(1)
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
// Two Pointers (1 pass)
// Use a dummy node to handle edge cases
var dummy = new ListNode(0, head);
var slow = dummy;
var fast = dummy;
// Move fast pointer n + 1 ahead
for (int i = 0; i <= n; i++)
{
fast = fast.next;
}
// Iterate both pointers until fast = null
while (fast != null)
{
slow = slow.next;
fast = fast.next;
}
// Slow pointer will be pointing at node to remove
slow.next = slow.next.next;
return dummy.next;
}
}
#endregion
#region Iteration (Two Pass)
// Time O(n)
// Space O(1)
public class Solution
{
public ListNode RemoveNthFromEnd(ListNode head, int n)
{
// Dummy node simplifies edge cases
var dummy = new ListNode(0, head);
int len = 0;
var cur = head;
// Step 1: Find length
while (cur != null)
{
cur = cur.next;
len++;
}
// Step 2: Stop at node before nth from end
cur = dummy;
for (int i = 0; i < len - n; i++)
{
cur = cur.next;
}
// Step 3: Remove node and return head
cur.next = cur.next.next;
return dummy.next;
}
}
#endregion