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.

分析

代码

  1. // Merge Two Sorted Lists
  2. // 时间复杂度O(min(m,n)),空间复杂度O(1)
  3. public class Solution {
  4. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  5. if (l1 == null) return l2;
  6. if (l2 == null) return l1;
  7. ListNode dummy = new ListNode(-1);
  8. ListNode p = dummy;
  9. for (; l1 != null && l2 != null; p = p.next) {
  10. if (l1.val > l2.val) { p.next = l2; l2 = l2.next; }
  11. else { p.next = l1; l1 = l1.next; }
  12. }
  13. p.next = l1 != null ? l1 : l2;
  14. return dummy.next;
  15. }
  16. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/sorting/merge-sort/merge-two-sorted-lists.html