Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 28, 2015 20:06
Show Gist options
  • Save dmnugent80/290ce1adc0a7e7e564c4 to your computer and use it in GitHub Desktop.
Save dmnugent80/290ce1adc0a7e7e564c4 to your computer and use it in GitHub Desktop.
Merge Two Sorted Linked Lists
/**
* 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) {
if (l1 == null && l2 == null) return null;
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode temp = new ListNode(0);
ListNode prev = temp;
while (l1 != null && l2 != null){
if (l1.val <= l2.val){
prev.next = l1;
l1 = l1.next;
}
else{
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
if (l1 != null){
prev.next = l1;
}
if (l2 != null){
prev.next = l2;
}
return temp.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment