-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove-nth-node-from-end-of-list.go
More file actions
73 lines (65 loc) · 1.22 KB
/
remove-nth-node-from-end-of-list.go
File metadata and controls
73 lines (65 loc) · 1.22 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
package main
import (
"fmt"
)
// ListNode is the node type for linked list
type ListNode struct {
Val int
Next *ListNode
}
func removeNthFromEnd(head *ListNode, n int) (first *ListNode) {
first = head
var r *ListNode
for ; head != nil; head = head.Next {
if n <= 0 {
if r == nil {
r = first
continue
}
r = r.Next
continue
}
n--
}
if r == nil {
return first.Next
}
if r.Next == nil {
r.Next = nil
return
}
r.Next = r.Next.Next
return
}
func main() {
test1 := &ListNode{1, nil}
test2 := 1
// fmt.Printf("Testing %v \n", test1)
result := removeNthFromEnd(test1, test2)
fmt.Printf("Yields %v\n", result)
test1 = &ListNode{1, &ListNode{2, &ListNode{3, nil}}}
test2 = 1
// fmt.Printf("Testing %v \n", test1)
result = removeNthFromEnd(test1, test2)
fmt.Printf("Yields %v\n", result)
test1 = &ListNode{1, &ListNode{2, &ListNode{3, nil}}}
test2 = 2
// fmt.Printf("Testing %v \n", test1)
result = removeNthFromEnd(test1, test2)
fmt.Printf("Yields %v\n", result)
test1 = &ListNode{1, &ListNode{2, &ListNode{3, nil}}}
test2 = 3
// fmt.Printf("Testing %v \n", test1)
result = removeNthFromEnd(test1, test2)
fmt.Printf("Yields %v\n", result)
}
/*
[1]
1
[1,2,3]
1
[1,2,3]
2
[1,2,3]
3
*/