题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
链表结构:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/
解法一、常规思路
public class Solution { public ListNode Merge(ListNode l1, ListNode l2) { ListNode head = new ListNode(0), p = head; // head头结点,避免找不到链表头 while (l1 != null && l2 != null) { if (l1.val <= l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } p.next = l1 != null ? l1: l2; return head.next; } }
解法二、递归解法
public class Solution { public ListNode Merge(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1); // head头结点,防止找不到头 doMerge(head, l1, l2); return head.next; } // 递归辅助函数 private void doMerge(ListNode head, ListNode l1, ListNode l2) { if (l1 == null || l2 == null) { head.next = l1 == null ? l2 : l1; // 三元运算写起来简单但是性能很差 return ; // 递归终止条件 } if (l1.val <= l2.val) { head.next = l1; doMerge(head.next, l1.next, l2); } else { head.next = l2; doMerge(head.next, l1, l2.next); } } }