-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathremoveNthFromEnd.go
More file actions
74 lines (60 loc) · 1.35 KB
/
Copy pathremoveNthFromEnd.go
File metadata and controls
74 lines (60 loc) · 1.35 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
66
67
68
69
70
71
72
73
74
/* https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description
Given a linked list, remove the n^th node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
*/
package lll
func removeNthFromEnd(head *ListNode, n int) *ListNode {
res := &ListNode{}
slow, fast := res, head
slow.Next = head
// Move fast in front so that the gap between slow and fast becomes n
for i := 1; i <= n; i++ {
fast = fast.Next
}
// Move fast to the end, maintaining the gap
for fast != nil {
slow = slow.Next
fast = fast.Next
}
// Skip the desired node
slow.Next = slow.Next.Next
return res.Next
}
/*
func removeNthFromEnd(head *ListNode, n int) *ListNode {
i, total := 0, 0
slow, fast := head, head
for fast != nil && fast.Next != nil {
i++
slow, fast = slow.Next, fast.Next.Next
}
if fast == nil {
total = i * 2
} else {
total = i*2 + 1
}
if total-n == 0 {
return head.Next
}
var res, cur, ptr *ListNode
if total-n > i {
res, cur, ptr = head, slow, slow.Next
i++
} else {
i = 0
res, ptr = head, head
}
for ; i < total-n; i++ {
cur, ptr = ptr, ptr.Next
}
if cur != nil {
cur.Next = ptr.Next
}
return res
}
*/