1.合并两个有序链表
java实现
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode newHead = new ListNode(-1);
ListNode res = newHead;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
newHead.next = list1;
list1 = list1.next;
} else if (list1.val > list2.val) {
newHead.next = list2;
list2 = list2.next;
} else { //相等的情况,分别接两个链
newHead.next = list2;
list2 = list2.next;
newHead = newHead.next;
newHead.next = list1;
list1 = list1.next;
}
newHead = newHead.next;
}
while (list1 != null) {
newHead.next = list1;
list1 = list1.next;
newHead = newHead.next;
}
while (list2 != null) {
newHead.next = list2;
list2 = list2.next;
newHead = newHead.next;
}
return res.next;
}
python实现
def mergeTwoLists(self, list1, list2):
phead = ListNode(0)
p = phead;
while list1 and list2:
if list1.val <= list2.val:
p.next = list1
list1 = list1.next
else:
p.next = lsit2
list2 = list2.next
p = p.next
while list1 is not None:
p.next = list1
while list2 is not None:
p.next = list2
return phead.next
2.合并K个链表
先合并两个,之后再将后面的逐步合并。即循环调用合并两个链表的方法
3.一道很无聊的好题
给你两个链表 list1 和 list2 ,它们包含的元素分别为 n 个和 m 个。
请你将 list1 中第 a 个节点到第 b 个节点删除,并将list2 接在被删除节点的位置。
示例 1:
输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
输出:[0,1,2,1000000,1000001,1000002,5]
解释:我们删除 list1 中第三和第四个节点,并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。
Java代码
public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2){
ListNode pre1 = list1, post1 = list1, post2 = list2;
int i=0, j=0;
//先找到要删除节点的位置
while (pre1 != null && post1 != null && j<b){
if(i != a-1){
pre1 = pre1.next;
i++;
}
if(j != b){
post1 = post1.next;
j++;
}
}
//获取删除节点后面一个位置
post1 = post1.next;
//找到list2的尾节点
while(post2 != null){
post2 = post2.next;
}
//链表拼接
pre1.next = list2;
post2.next = post1;
return list1;
}
python代码
def mergeInBetween(self, list1, a, b, list2):
dummy = ListNode(0)
dummy.next = list1
tmp1,tmp2 = dummy
l1,l2 = a, b+1
while l1:
tmp1 = tmp1.next
l1 -= 1
while l2:
tmp2 = tmp2.next
l2 -= 1
tmp1.next = list2
while list2.next:
list2 =list2.next
list2.next = tmp2
return dummy.next