funcremoveNthFromEnd(head *ListNode, n int) *ListNode { dummyHead := &ListNode{0, head}
first := dummyHead // 移动 first 指针,使得它超前 second 指针 n 个节点 for i := 0; i < n; i++ { first = first.Next } second := dummyHead
// 同时移动两个指针,直至 first 指针到最后一个节点,此时 second 指针就是要删除节点的前驱节点 for first.Next != nil { first = first.Next second = second.Next }
second.Next = second.Next.Next // 执行删除
return dummyHead.Next }
栈
所有节点依次入栈,然后弹出第 n 个节点就是要删除的节点,且此时栈顶正好是它前一个节点。
1 2 3 4 5 6 7 8 9 10 11 12
funcremoveNthFromEnd(head *ListNode, n int) *ListNode { dummy := &ListNode{0, head} first, second := head, dummy for i := 0; i < n; i++ { first = first.Next } for ; first != nil; first = first.Next { second = second.Next } second.Next = second.Next.Next return dummy.Next }