Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2458 from lavaicer/master
Browse files Browse the repository at this point in the history
优化 19. 删除链表的倒数第 N 个结点 go 代码
  • Loading branch information
youngyangyang04 authored Mar 16, 2024
2 parents 45f4f5c + a1e8af3 commit ceec07f
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions problems/0019.删除链表的倒数第N个节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,20 +165,17 @@ class Solution:
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummyHead := &ListNode{}
dummyHead.Next = head
cur := head
prev := dummyHead
i := 1
for cur != nil {
cur = cur.Next
if i > n {
prev = prev.Next
}
i++
}
prev.Next = prev.Next.Next
return dummyHead.Next
dummyNode := &ListNode{0, head}
fast, slow := dummyNode, dummyNode
for i := 0; i <= n; i++ { // 注意<=,否则快指针为空时,慢指针正好在倒数第n个上面
fast = fast.Next
}
for fast != nil {
fast = fast.Next
slow = slow.Next
}
slow.Next = slow.Next.Next
return dummyNode.Next
}
```

Expand Down

0 comments on commit ceec07f

Please sign in to comment.