题目描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:假设两链表分别为list1和list2,若一个为空,则返回另外一个链表的头结点。若两个都不为空,设置head和curNode两个变量,head记录头节点,curNode记录当前节点。按照两链表的值的大小更新当前curNode。
链表结构:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
递归:
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
while(list1 != null && list2 != null){
if(list1.val < list2.val){
list1.next = Merge(list1.next, list2);
return list1;
}else{
list2.next = Merge(list1, list2.next);
return list2;
}
}
return list1;
}
非递归写法:
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
ListNode head = null;
ListNode curNode = null;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
if(head == null){
head = curNode = list1;
}else{
curNode.next = list1;
curNode = curNode.next;
}
list1 = list1.next;
}else{
if(head == null){
head = curNode = list2;
}else{
curNode.next = list2;
curNode = curNode.next;
}
list2 = list2.next;
}
}
if(list1 == null){
curNode.next = list2;
}
if(list2 == null){
curNode.next = list1;
}
return head;
}