Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:19
Show Gist options
  • Save HDegano/070b1dccc5682930eceb to your computer and use it in GitHub Desktop.
Save HDegano/070b1dccc5682930eceb to your computer and use it in GitHub Desktop.
Merge Two Sorted List
/**
* 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