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.
Time complexity: O(m+n)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // Start typing your Java solution below // DO NOT write main() function ListNode root = null; ListNode node = null; while (l1 != null && l2 != null) { if (l1.val < l2.val) { if (node == null) { node = l1; root = node; } else { node.next = l1; node = node.next; } l1 = l1.next; } else { if (node == null) { node = l2; root = node; } else { node.next = l2; node = node.next; } l2 = l2.next; } } while (l1 != null) { if (node == null) { node = l1; root = node; } else { node.next = l1; node = node.next; } l1 = l1.next; } while (l2 != null) { if (node == null) { node = l2; root = node; } else { node.next = l2; node = node.next; } l2 = l2.next; } return root; } }
No comments:
Post a Comment