合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回, 新链表是通过拼接给定的两个链表的所有节点组成的。
例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解析:
1>.定义一个新链表
ListNode result = null;
2>.定义两个引用,分别指向两个链表,方便两个数进行比较
ListNode cur1 = l1;
ListNode cur2 = l2;
3>.分情况讨论:
cur1.val<=cur2.val;
cur1.val>cur2.val;
取数,将所取得数尾插到新链表中
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode result = null;
ListNode last = null;
ListNode cur1 = l1;
ListNode cur2 = l2;
while (cur1 != null && cur2 != null) {
if (cur1.val <= cur2.val) {
ListNode next = cur1.next;
if (result == null) {
result = cur1;
} else {
last.next = cur1;
}
last = cur1;
cur1 = next;
} else {
ListNode next = cur2.next;
if (result == null) {
result = cur2;
} else {
last.next = cur2;
}
last = cur2;
cur2 = next;
}
}
if (cur1 != null) {
last.next = cur1;
} else {
last.next = cur2;
}
return result;
}
}
public Node mergeTwoLists(Node list1,Node list2){
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
Node prehead=new Node(-1);
Node prev=prehead;
while(list1!=null && list2!=null){
if(list1.val <= list2.val){
prev.next=list1;
list1=list1.next;
}else{
prev.next=list2;
list2=list2.next;
}
prev=prev.next;
}
prev.next=list1==null?list2:list1;
return prehead.next;
}
递归方法也可以将两个链表进行合并:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}