1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// @Title: 删除链表的倒数第 N 个结点 (Remove Nth Node From End of List)
// @Author: 15816537946@163.com
// @Date: 2020-10-31 10:12:22
// @Runtime: 0 ms
// @Memory: 2.2 MB
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	if head == nil {
		return head
	}

	tmp := new(ListNode)
	tmp.Next = head
	lo := tmp
	hi := tmp

	for i := 0; i <= n; i++ {
		hi = hi.Next
	}

	for hi != nil {
		hi = hi.Next
		lo = lo.Next
	}

	lo.Next = lo.Next.Next

	return tmp.Next
}