Skip to content

Instantly share code, notes, and snippets.

@jporcelli
Created September 3, 2014 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jporcelli/f28105f71386face2497 to your computer and use it in GitHub Desktop.
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.
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