mirror of
https://gitlab.com/game-loader/hugo.git
synced 2025-04-20 05:52:07 +08:00
leetcode update
This commit is contained in:
parent
e967f7682d
commit
de7024a2c9
@ -1678,3 +1678,73 @@ func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
|
|||||||
### 总结
|
### 总结
|
||||||
|
|
||||||
本题保存了首尾两个指针的地址, 是典型的用空间换时间的思路, 不过实际应用过程中可能还要根据语言注意被动态分配出去的空间回收的问题.
|
本题保存了首尾两个指针的地址, 是典型的用空间换时间的思路, 不过实际应用过程中可能还要根据语言注意被动态分配出去的空间回收的问题.
|
||||||
|
|
||||||
|
## day24 2024-03-21
|
||||||
|
|
||||||
|
### 206. Reverse Linked
|
||||||
|
|
||||||
|
Given the head of a singly linked list, reverse the list, and return the reversed list.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### 题解
|
||||||
|
|
||||||
|
本题相当基础, 是一道简单题, 只需要将链表整个反转过来即可. 用一个变量保存当前访问的节点的前一个节点的指针, 将当前节点的next修改为指向前一个节点的指针, 遍历整个链表即可. 注意处理边界情况(头指针为0).
|
||||||
|
|
||||||
|
### 代码
|
||||||
|
|
||||||
|
```go
|
||||||
|
/**
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* type ListNode struct {
|
||||||
|
* Val int
|
||||||
|
* Next *ListNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
func reverseList(head *ListNode) *ListNode {
|
||||||
|
var before *ListNode
|
||||||
|
current := head
|
||||||
|
for current!=nil && current.Next!=nil {
|
||||||
|
temp := current.Next
|
||||||
|
current.Next = before
|
||||||
|
before = current
|
||||||
|
current = temp
|
||||||
|
}
|
||||||
|
if head!=nil{
|
||||||
|
current.Next = before
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 总结
|
||||||
|
|
||||||
|
本题是一道基础题, 在查看他人解答的过程中发现本题也可以将链表数据全部复制出来, 再遍历链表逆序赋值即可. 示例代码如下
|
||||||
|
|
||||||
|
```go
|
||||||
|
/**
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* type ListNode struct {
|
||||||
|
* Val int
|
||||||
|
* Next *ListNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
func reverseList(head *ListNode) *ListNode {
|
||||||
|
arr := []int{}
|
||||||
|
|
||||||
|
node := head
|
||||||
|
|
||||||
|
for node != nil {
|
||||||
|
arr = append(arr, node.Val)
|
||||||
|
node = node.Next
|
||||||
|
}
|
||||||
|
|
||||||
|
node = head
|
||||||
|
for i := len(arr); i > 0; i-- {
|
||||||
|
node.Val = arr[i-1]
|
||||||
|
node = node.Next
|
||||||
|
}
|
||||||
|
|
||||||
|
return head
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Loading…
Reference in New Issue
Block a user