19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点

快慢指针

伪头节点真香,删除头节点很方便

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	if head.Next == nil {
		return nil
	}
	fakeHead := &ListNode{Next: head}
	pre, p, q := fakeHead, head, head
	for i := 0; i < n; i++ {
		q = q.Next
	}
	for q != nil {
		pre = p
		p = p.Next
		q = q.Next
	}
	pre.Next = p.Next
	return fakeHead.Next
}