-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-nth-node-from-end-of-list.go
58 lines (53 loc) · 1.11 KB
/
remove-nth-node-from-end-of-list.go
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
package main
import (
"fmt"
)
type ListNode struct {
Val int
Next *ListNode
}
func (head *ListNode) String() string {
list := ""
for temp := head; temp != nil; temp = temp.Next {
if temp == head {
list = fmt.Sprintf("%d", temp.Val)
} else {
list = fmt.Sprintf("%s->%d", list, temp.Val)
}
}
return list
}
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if head == nil || head.Next == nil && n == 1 {
return nil
}
if n <= 0 {
return head
}
count := 0
for temp := head; temp != nil; temp = temp.Next {
count++
}
if count >= n {
index := count - n + 1
if index == 1 {
return head.Next
}
currentPos := 2
for previous, current := head, head.Next; current != nil; previous, current = previous.Next, current.Next {
if currentPos == index {
previous.Next = current.Next
break
}
currentPos++
}
}
return head
}
func main() {
list := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, nil}}}}
// fmt.Println(removeNthFromEnd(list, 1))
// fmt.Println(removeNthFromEnd(list, 2))
// fmt.Println(removeNthFromEnd(list, 3))
fmt.Println(removeNthFromEnd(list, 4))
}