美文网首页leetcode
19. Remove Nth Node From End of

19. Remove Nth Node From End of

作者: AnakinSun | 来源:发表于2019-03-22 13:25 被阅读3次

快慢指针,快指针先前进n步,然后两个指针一起前进,当快指针走到末尾的时候,慢指针所在的位置,就是目标位置
需要注意判断空节点情况

func removeNthFromEnd(head *ListNode, n int) *ListNode {
   cur := head
   last := head
   for i := 0; i < n; i++ {
       if cur.Next != nil {
           cur = cur.Next
       } else {
           return head.Next
       }
   }
   for cur.Next != nil {
       cur = cur.Next
       last = last.Next
   }
   last.Next = last.Next.Next
   return head
}

相关文章

网友评论

    本文标题:19. Remove Nth Node From End of

    本文链接:https://www.haomeiwen.com/subject/zsblvqtx.html