Merge Two Sorted Lists
https://leetcode.com/problems/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.
算法思想:
连接两个排好序(假设升序,降序类似)的链表,这是一道典型的递归题。
比较两个链表的第一个元素,如果l1的第一个node的值要比l2的第一个node的值小,那么新的链表的第一个node就是l1的第一个node,第二个node开始就是l1的第二个node和l2连接起来的list;反之同。
程序清单:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public 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;
}
}
}