本文共 973 字,大约阅读时间需要 3 分钟。
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4输出:1->1->2->3->4->4
public class MergeList { public static void main(String[] args) { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode l2 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode listNode = mergeTwoLists(l1, l2); System.out.println(listNode); } /** * 使用递归合并 * @param l1 * @param l2 * @return */ public static ListNode mergeTwoLists(ListNode l1, ListNode l2){ if (l1 == null){ return l2; } if (l2 == null){ return l1; } ListNode head = null; if (l1.val < l2.val){ head = l1; head.next = mergeTwoLists(l1.next,l2); }else{ head = l2; head.next = mergeTwoLists(l1,l2.next); } return head; }}
转载地址:http://xvslf.baihongyu.com/