Advertisement
1988coder

21. Merge Two Sorted Lists

Jan 7th, 2019
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/add-two-numbers/
  2.  
  3. //   Definition for singly-linked list.
  4. class ListNode {
  5.     int val;
  6.     ListNode next;
  7.  
  8.     ListNode(int x) {
  9.         val = x;
  10.     }
  11. }
  12.  
  13. /**
  14.  * Iterative Solution
  15.  *
  16.  * Time Complexity: O(min(M, N))
  17.  *
  18.  * Space Complexity: O(1)
  19.  *
  20.  * M = Length of the input list l1. N = Length of the input list l2.
  21.  */
  22. class Solution1 {
  23.     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  24.         if (l1 == null) {
  25.             return l2;
  26.         }
  27.         if (l2 == null) {
  28.             return l1;
  29.         }
  30.  
  31.         ListNode dummyHead = new ListNode(-1);
  32.         ListNode prevNode = dummyHead;
  33.         ListNode p = l1;
  34.         ListNode q = l2;
  35.  
  36.         while (p != null && q != null) {
  37.             if (p.val <= q.val) {
  38.                 prevNode.next = p;
  39.                 p = p.next;
  40.             } else {
  41.                 prevNode.next = q;
  42.                 q = q.next;
  43.             }
  44.             prevNode = prevNode.next;
  45.             prevNode.next = null;
  46.         }
  47.  
  48.         prevNode.next = p == null ? q : p;
  49.         return dummyHead.next;
  50.     }
  51. }
  52.  
  53. /**
  54.  * Recursive Solution
  55.  *
  56.  * Time Complexity: O(min(M, N))
  57.  *
  58.  * Space Complexity: O(min(M, N))
  59.  *
  60.  * M = Length of the input list l1. N = Length of the input list l2.
  61.  */
  62. class Solution2 {
  63.     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  64.         if (l1 == null) {
  65.             return l2;
  66.         }
  67.         if (l2 == null) {
  68.             return l1;
  69.         }
  70.  
  71.         return mergeTwoListsHelper(l1, l2);
  72.     }
  73.  
  74.     private ListNode mergeTwoListsHelper(ListNode p, ListNode q) {
  75.         if (p == null) {
  76.             return q;
  77.         }
  78.         if (q == null) {
  79.             return p;
  80.         }
  81.         if (p.val <= q.val) {
  82.             p.next = mergeTwoListsHelper(p.next, q);
  83.             return p;
  84.         } else {
  85.             q.next = mergeTwoLists(p, q.next);
  86.             return q;
  87.         }
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement