Last active
August 29, 2015 14:19
-
-
Save HDegano/070b1dccc5682930eceb to your computer and use it in GitHub Desktop.
Merge Two Sorted List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* public int val; | |
* public ListNode next; | |
* public ListNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public ListNode MergeTwoLists(ListNode l1, ListNode l2) { | |
if(l1 == null && l2 == null) return null; | |
if(l1 != null && l2 == null) return l1; | |
if(l2 != null && l1 == null) return l2; | |
ListNode newHead = null; | |
if(l1.val < l2.val){ | |
newHead = l1; | |
newHead.next = MergeTwoLists(l1.next, l2); | |
} | |
else | |
{ | |
newHead = l2; | |
newHead.next = MergeTwoLists(l1, l2.next); | |
} | |
return newHead; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment