This commit is contained in:
2026-06-21 13:11:31 +10:00
parent 3bce899398
commit 35c362681e
6 changed files with 533 additions and 0 deletions
+83
View File
@@ -0,0 +1,83 @@
package top100liked
import (
"fmt"
"testing"
)
// https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked
type ListNode struct {
Val int
Next *ListNode
}
// func removeNthFromEnd(head *ListNode, n int) *ListNode {
// pre := &ListNode{Next: head}
// p := head
// l := 0
// for p != nil {
// l++
// p = p.Next
// }
// p1 := pre
// p2 := pre.Next.Next
// for range l - n {
// p1 = p1.Next
// p2 = p2.Next
// }
// p1.Next = p2
// return pre.Next
// }
// 双指针
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummy := &ListNode{0, head}
first, second := head, dummy
for range n {
first = first.Next
}
for first != nil {
first = first.Next
second = second.Next
}
second.Next = second.Next.Next
return dummy.Next
}
func Test(t *testing.T) {
input1 := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 3,
Next: &ListNode{
Val: 4,
Next: &ListNode{
Val: 5,
Next: nil,
},
},
},
},
}
input2 := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: nil,
},
}
output := removeNthFromEnd(input1, 2)
for output != nil {
fmt.Print(output.Val, " ")
output = output.Next
}
fmt.Println()
output = removeNthFromEnd(input2, 1)
for output != nil {
fmt.Print(output.Val, " ")
output = output.Next
}
}