From e967f7682d37c9610ce5c6e79b76bd755234ef4a Mon Sep 17 00:00:00 2001 From: gameloader Date: Wed, 20 Mar 2024 19:20:54 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 32f0509..f6e151c 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -1616,3 +1616,65 @@ func leastInterval(tasks []byte, n int) int { return len(tasks) + idleSlots } ``` + +## day23 2024-03-20 + +### 1669. Merge In Between Linked Lists + +You are given two linked lists: list1 and list2 of sizes n and m respectively. + +Remove list1's nodes from the ath node to the bth node, and put list2 in their place. + +The blue edges and nodes in the following figure indicate the result: + +![0320kDnwlxpwmKhB](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0320kDnwlxpwmKhB.png) + +Build the result list and return its head. + +![03200deJDZCQpgs3](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/03200deJDZCQpgs3.png) + +### 题解 + +本题为将链表中某段替换为指定的链表, 只需要遍历链表, 保存需要替换部分首尾两个节点的指针即可, 需要注意边界情况的处理, 即替换开头某段或者结尾某段链表时要处理空指针. + +### 代码 + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode { + count := 0 + var before *ListNode + var after *ListNode + current := list1 + head := list1 + for count <= b { + if count == a-1 { + before = current + } + count++ + current = current.Next + } + after = current + if before == nil { + head = list2 + } else { + before.Next = list2 + } + current = list2 + for current.Next != nil { + current = current.Next + } + current.Next = after + return head +} +``` + +### 总结 + +本题保存了首尾两个指针的地址, 是典型的用空间换时间的思路, 不过实际应用过程中可能还要根据语言注意被动态分配出去的空间回收的问题.