题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
两种解法:递归和非递归
参考代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
//递归解法
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
else if(list2 == null)
return list1;
ListNode mergehead = null;
if(list1.val <= list2.val){
mergehead = list1;
mergehead.next = Merge(list1.next,list2);
}else{
mergehead = list2;
mergehead.next = Merge(list1, list2.next);
}
return mergehead;
}
}
//非递归解法
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
else if(list2 == null)
return list1;
ListNode mergehead = null;
if(list1.val <= list2.val){
mergehead = list1;
list1 = list1.next;
}else{
mergehead = list2;
list2 = list2.next;
}
ListNode cur = mergehead;
while(list1 != null && list2 != null){
if(list1.val <= list2.val){
cur.next = list1;
list1 = list1.next;
}else{
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if(list1 == null)
cur.next = list2;
else if(list2 == null)
cur.next = list1;
return mergehead;
}
}
同时有一个和这个题类似的题
题目:合并K个排序链表
题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
思路
想办法转成合并两个排序链表再做
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if(lists.length==0){ return null; } else if(lists.length==1){ return lists[0]; } else if(lists.length==2){ return mergeTwoList(lists[0],lists[1]); }else{ ListNode[] l1=new ListNode[lists.length/2]; ListNode[] l2=new ListNode[lists.length-lists.length/2]; for(int i=0;i<lists.length;i++){ if(i<lists.length/2) l1[i]=lists[i]; else l2[i-lists.length/2]=lists[i]; } return mergeTwoList(mergeKLists(l1),mergeKLists(l2)); } } public ListNode mergeTwoList(ListNode l1,ListNode l2){ if(l1==null){ return l2; } if(l2==null){ return l1; } if(l1.val>=l2.val){ l2.next=mergeTwoList(l1,l2.next); return l2; }else{ l1.next=mergeTwoList(l1.next,l2); return l1; } } }
本文详细介绍了如何合并两个单调递增的链表,并保持合并后链表的单调不减规则。提供了递归和非递归两种解法的代码实现,同时讨论了如何将此方法应用于合并K个排序链表的问题。

被折叠的 条评论
为什么被折叠?



