mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-07 01:44:56 +08:00
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:
@ -17,13 +17,16 @@ type ListNode = structures.ListNode
|
|||||||
|
|
||||||
// 解法一
|
// 解法一
|
||||||
func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
||||||
|
if head == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
var fast, slow *ListNode
|
var fast, slow *ListNode
|
||||||
fast = head
|
fast = head
|
||||||
slow = head
|
slow = head
|
||||||
step := 0
|
step := 0
|
||||||
for i := 0; i < n; i++ {
|
for i := 0; i < n; i++ {
|
||||||
// n maybe much larger than length of linklist
|
// 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
|
return head
|
||||||
}
|
}
|
||||||
fast = fast.Next
|
fast = fast.Next
|
||||||
|
Reference in New Issue
Block a user