合并两个有序链表,第一个想法就是归并排序。
java实现代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);
ListNode temp = listNode;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
temp.next = l1;
temp = temp.next;
l1 = l1.next;
}else{
temp.next = l2;
temp = temp.next;
l2 = l2.next;
}
}
while(l1 != null){
temp.next = l1;
temp = temp.next;
l1 = l1.next;
}
while(l2 != null){
temp.next = l2;
temp = temp.next;
l2 = l2.next;
}
return listNode.next;
}
}
执行效果: