上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
}
};
golang 解法, 执行用时: 96 ms, 内存消耗: 7 MB, 提交时间: 2022-11-16 11:46:53
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
var preNode, postNode *ListNode
p1 := list1
i := 0
for p1 != nil {
i++
preNode = p1 //preNode最后走到list2尾节点
if i == a {
postNode = p1.Next // postNode 走到了list1索引为a的节点
p1.Next = list2
} else {
p1 = p1.Next
}
}
i = a
p1 = postNode // p1从list1的a开始
for p1 != nil {
if i == b {
preNode.Next = p1.Next // list2尾结点指向list1索引为b的节点
break
} else {
p1 = p1.Next
}
i++
}
return list1
}
python3 解法, 执行用时: 376 ms, 内存消耗: 21.7 MB, 提交时间: 2022-11-16 11:36:23
# 模拟,存list后再拼接
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
phead = list1
l = list()
while list1:
l.append(list1)
list1 = list1.next
r = list()
while list2:
r.append(list2)
list2 = list2.next
l1 = l[0:a]
l2 = l[b+1:]
l1[-1].next = r[0]
r[-1].next = l2[0]
return phead
java 解法, 执行用时: 1 ms, 内存消耗: 44.8 MB, 提交时间: 2022-11-16 11:35:07
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
ListNode dummyNode = new ListNode(0, list1);
ListNode cur = dummyNode;
int index = 0;
while (index < a) {
cur = cur.next;
index++;
}
ListNode preA = cur; // 获得节点a的前驱节点
while (index <= b) {
cur = cur.next;
index++;
}
ListNode succB = cur.next; // 获得节点b的后继节点
cur = list2;
while (cur.next != null) { // 获得list的尾节点
cur = cur.next;
}
preA.next = list2;
cur.next = succB;
return dummyNode.next;
}
}