Created
September 3, 2014 02:05
-
-
Save jporcelli/f28105f71386face2497 to your computer and use it in GitHub Desktop.
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.
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
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { | |
ListNode cur = null; | |
ListNode head = null; | |
while(l1 != null || l2 != null){ | |
if(l1 != null && l2 != null && l1.val <= l2.val){ | |
if(head == null){ | |
head = l1; | |
cur = head; | |
l1 = l1.next; | |
}else{ | |
cur.next = l1; | |
cur = cur.next; | |
l1 = l1.next; | |
} | |
}else if(l1 != null && l2 != null && l2.val < l1.val){ | |
if(head == null){ | |
head = l2; | |
cur = head; | |
l2 = l2.next; | |
}else{ | |
cur.next = l2; | |
cur = cur.next; | |
l2 = l2.next; | |
} | |
}else if(l1 == null && l2 != null){ | |
if(head == null){ | |
head = l2; | |
cur = head; | |
l2 = l2.next; | |
}else{ | |
cur.next = l2; | |
cur = cur.next; | |
l2 = l2.next; | |
} | |
}else if(l2 == null && l1 != null){ | |
if(head == null){ | |
head = l1; | |
cur = head; | |
l1 = l1.next; | |
}else{ | |
cur.next = l1; | |
cur = cur.next; | |
l1 = l1.next; | |
} | |
} | |
} | |
return head; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment