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

题解

两次遍历,第一次算出链表的长度,第二次从前往后删除指定节点

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
node := head
m := 0
for head != nil {
m++
head = head.Next
}
head = node
if m == n {
return head.Next
}
for i := 0; i < m-n-1; i++ {
node = node.Next
}
node.Next = node.Next.Next
return head
}