-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
19. Remove Nth Node From End of List.go
70 lines (65 loc) · 1.09 KB
/
19. 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
59
60
61
62
63
64
65
66
67
68
69
70
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// 解法一
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummyHead := &ListNode{Next: head}
preSlow, slow, fast := dummyHead, head, head
for fast != nil {
if n <= 0 {
preSlow = slow
slow = slow.Next
}
n--
fast = fast.Next
}
preSlow.Next = slow.Next
return dummyHead.Next
}
// 解法二
func removeNthFromEnd1(head *ListNode, n int) *ListNode {
if head == nil {
return nil
}
if n <= 0 {
return head
}
current := head
len := 0
for current != nil {
len++
current = current.Next
}
if n > len {
return head
}
if n == len {
current := head
head = head.Next
current.Next = nil
return head
}
current = head
i := 0
for current != nil {
if i == len-n-1 {
deleteNode := current.Next
current.Next = current.Next.Next
deleteNode.Next = nil
break
}
i++
current = current.Next
}
return head
}