题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题解
递归版本
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode head1,ListNode head2) {
if(head1 == null)
return head2;
if(head2 == null)
return head1;
ListNode head = null;
if(head1.val < head2.val) {
head = head1;
head.next = Merge(head1.next, head2);
} else {
head = head2;
head.next = Merge(head1, head2.next);
}
return head;
}
}
非递归版本
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode head1,ListNode head2) {
if(head1 == null)
return head2;
if(head2 == null)
return head1;
ListNode head = null;
if(head1.val < head2.val) {
head = head1;
head1 = head1.next;
} else {
head = head2;
head2 = head2.next;
}
ListNode cur = head;
while(head1 != null || head2 != null) {
if(head1 == null) {
cur.next = head2;
return head;
} else if(head2 == null) {
cur.next = head1;
return head;
} else if(head1.val < head2.val) {
cur.next = head1;
head1 = head1.next;
cur = cur.next;
} else {
cur.next = head2;
head2 = head2.next;
cur = cur.next;
}
}
return head;
}
}