题解一
采用递归,每次取出两个链表中较小的一个节点,接下来Merge取后剩下的两个链表,一直到两个链表中有一个为空。
图解:
每次递归,让temp为两个链表中较小的节点,temp.next为下一次递归中较小的节点,每次递归返回temp给上一个节点。
/*
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;
}
if(list2 == null) {
return list1;
}
ListNode temp = null;
if(list1 != null && list2 != null) {
if(list1.val < list2.val) {
temp = list1;
list1.next = Merge(list1.next, list2);
} else {
temp = list2;
list2.next = Merge(list1, list2.next);
}
}
return temp;
}
}
题解二
不用递归,定义一个新的链表,定义一个辅助指针temp来遍历新链表,注意要定义一个指针head来保存新链表的第一个节点,否则遍历到最后无法找到新链表的头部。用两个指针first和second分别遍历两个链表,每次取较小的节点作为新链表的下一个节点,较小节点的指针后移,直到两个链表中有一个为空。
/*
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;
}
if(list2 == null) {
return list1;
}
ListNode first = list1;
ListNode second = list2;
ListNode temp = new ListNode(-1);
ListNode head = temp;
while(first != null && second != null) {
if(first.val > second.val) {
temp.next = second;
second = second.next;
temp = temp.next;
} else {
temp.next = first;
first = first.next;
temp = temp.next;
}
}
if(first == null) {
temp.next = second;
}
if(second == null) {
temp.next = first;
}
return head.next;
}
}