Question
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-in-between-linked-lists/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Ideas
1、Answer( Java ) - 简单链表操作
解法思路:简单链表操作
👍定位 list1
左右截断的节点以及 list2
中右边界的节点位置
Code
/**
* @author Listen 1024
* @description 1669. 合并两个链表(两个链表的合并)
* 时间复杂度O(n) n = max(length(list1) length(list2))
* 空间复杂度O(1)
* @date 2022-07-12 23:12
*/
/**
* 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 cur = list1;
ListNode left = null;
ListNode right = null;
for (int i = 0; i < b + 1; i++) {
//寻找左边截断的节点
if (i == a - 1) {
left = cur;
}
cur = cur.next;
//寻找右边截断的节点
if (i == b) {
right = cur;
}
}
//确定 list2 右边界的节点
cur = list2;
while (cur.next != null) {
cur = cur.next;
}
cur.next = right;
left.next = list2;
return list1;
}
}