Update 19. Remove Nth Node From End of List.go

fix: when m(length of linkList) is 1 and n greater than m, will cause "nil pointer dereference"
This commit is contained in:
mfzzz
2021-04-15 02:35:26 +08:00
committed by GitHub
parent d47c2ec4c3
commit 858198e385

View File

@ -17,13 +17,16 @@ type ListNode = structures.ListNode
// 解法一
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if head == nil {
return nil
}
var fast, slow *ListNode
fast = head
slow = head
step := 0
for i := 0; i < n; i++ {
// n maybe much larger than length of linklist
if fast.Next == nil && step != 0 && step < n-1 {
if fast.Next == nil && step < n-1 {
return head
}
fast = fast.Next