Skip to content

Commit 29d7574

Browse files
committed
solution for Remove Nth Node From End of List O(N) runtime and memory, simple
1 parent 9f8b400 commit 29d7574

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// https://leetcode.com/problems/remove-nth-node-from-end-of-list/
2+
package main
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* type ListNode struct {
7+
* Val int
8+
* Next *ListNode
9+
* }
10+
*/
11+
12+
func removeNthFromEnd(head *ListNode, n int) *ListNode {
13+
current := head
14+
cnt := 0
15+
for ;current!=nil; {
16+
current = current.Next
17+
cnt++
18+
}
19+
20+
21+
22+
nPos := cnt - n - 1
23+
if nPos == -1 {
24+
return head.Next
25+
}
26+
if nPos < 0 {
27+
return nil
28+
}
29+
30+
31+
current = head
32+
for i:=0; i<nPos; i++ {
33+
current = current.Next
34+
}
35+
36+
if current.Next != nil {
37+
current.Next = current.Next.Next
38+
}
39+
40+
return head
41+
}
42+

0 commit comments

Comments
 (0)