一、问题描述
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
二、问题分析
原链表已经从小到大排好序,合并后产生的链表也要保持从小到大的顺序。
三、算法代码
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode cur = head;
ListNode l1_index = l1;
ListNode l2_index = l2;
while(l1_index != null && l2_index != null){
if(l1_index.val >= l2_index.val){
cur.next = l2_index;//保持合并后的链表也是从小到大的顺序
cur = cur.next;
l2_index = l2_index.next;
}else{
cur.next = l1_index;
cur = cur.next;
l1_index = l1_index.next;
}
}
if(l1_index != null){
cur.next = l1_index;
}
if(l2_index != null){
cur.next = l2_index;
}
return head.next;
}
}