mirror of
https://gitlab.com/game-loader/hugo.git
synced 2025-04-20 05:52:07 +08:00
add leetcode content
This commit is contained in:
parent
a5552c4d12
commit
7ff717e4c2
@ -341,3 +341,84 @@ func abs(val int) int {
|
||||
### 总结
|
||||
|
||||
注意一个go的语法问题, 如果在for range循环中两个变量都使用匿名变量, 则应该使用赋值运算符而不是创建并赋值运算符, 即`for _,_ = range slice` 而不是`for _,_ := range slice`. 这很可能是因为匿名变量默认为已经创建好的变量, 不需要再创建匿名变量本身了.
|
||||
|
||||
## day6 2024-03-03
|
||||
|
||||
### 19. Remove Nth Node From End of List
|
||||
|
||||
Given the head of a linked list, remove the nth node from the end of the list and return its head.
|
||||
|
||||

|
||||
|
||||
### 题解
|
||||
|
||||
给出了链表头, 要求移除从后到前的第n个节点. 如果想一遍遍历就完成这个任务. 就使用空间换时间, 使用一个数组保存所有的Next指针的值. 然后让倒数第n+1个元素的Next指针指向n个元素的Next指针即可, 注意处理链表只有一个元素的特殊情况.
|
||||
|
||||
### 代码
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
||||
var ptr []*ListNode
|
||||
current := head
|
||||
for current.Next != nil{
|
||||
ptr = append(ptr, current)
|
||||
current = current.Next
|
||||
}
|
||||
ptr = append(ptr, current)
|
||||
if(len(ptr) == 1){
|
||||
return nil
|
||||
}else if len(ptr) == n{
|
||||
return ptr[1]
|
||||
}else{
|
||||
ptr[len(ptr)-n-1].Next = ptr[len(ptr)-n].Next
|
||||
return head
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 总结
|
||||
|
||||
在题解中看到大部分使用的是快慢指针的解法, 快慢指针应该是本题想要的解法, 下面贴一个快慢指针的解法示例
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
|
||||
func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
||||
|
||||
dummyHead := &ListNode{-1, head}
|
||||
|
||||
cur, prevOfRemoval := dummyHead, dummyHead
|
||||
|
||||
for cur.Next != nil{
|
||||
|
||||
// n step delay for prevOfRemoval
|
||||
if n <= 0 {
|
||||
prevOfRemoval = prevOfRemoval.Next
|
||||
}
|
||||
|
||||
cur = cur.Next
|
||||
|
||||
n -= 1
|
||||
}
|
||||
|
||||
// Remove the N-th node from end of list
|
||||
nthNode := prevOfRemoval.Next
|
||||
prevOfRemoval.Next = nthNode.Next
|
||||
|
||||
return dummyHead.Next
|
||||
|
||||
}
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user