Skip to content

Instantly share code, notes, and snippets.

@linxinemily
Last active May 25, 2022 15:21
Show Gist options
  • Save linxinemily/03c00dc202c49d29df9020cfffe61869 to your computer and use it in GitHub Desktop.
Save linxinemily/03c00dc202c49d29df9020cfffe61869 to your computer and use it in GitHub Desktop.
19. Remove Nth Node From End of List
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
count_from_last := 0
return removeHelper(head, n, &count_from_last)
}
func removeHelper(node *ListNode, n int, count_from_last *int) *ListNode {
if node == nil {
return nil
}
node_next := removeHelper(node.Next, n, count_from_last)
//走到最底後會開始往回走,所以可以接著做其他事
node.Next = node_next // 更新 next(只有被刪除節點會回傳不同於原本的 next)
*count_from_last++
if *count_from_last == n {
return node_next
}
return node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment