LeetCode-21 Merge Two Sorted Lists(合并两个有序链表)
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 flag = new ListNode(0);
ListNode firstflag = flag;//标记第一个节点位置。
while (l1 != null && l2 != null) {//★
if(l1.val < l2.val){
flag.next = l1;
l1 = l1.next;
}else {
flag.next = l2;
l2 = l2.next;
}
flag = flag.next;
}
flag.next = l1 != null ? l1 : l2;
return firstflag.next;
}
}
事实上我认为在★的循环体内部能够进行优化。
在该处再加入while循环,判断L2新节点和l1当前节点的大小,如果依旧比l1当前节点大,则l2=l2.next~直到出现比当前节点大的节点,就将L2的上一个节点与l1连接,并l1的下一个节点继续判断...(重复刚刚l2的推进过程)...,这样可以减少连接次数。