Skip to content

Instantly share code, notes, and snippets.

@fever324
Last active August 29, 2015 14:09
Show Gist options
  • Save fever324/cd99dfad5044e94946cd to your computer and use it in GitHub Desktop.
Save fever324/cd99dfad5044e94946cd to your computer and use it in GitHub Desktop.
Merge Sorted 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 l1 != null ? l1 : l2;
}
ListNode head = null;
if(l1.val < l2.val) {
head = l1;
l1 = l1.next;
} else {
head = l2;
l2 = l2.next;
}
ListNode traverse = head;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
traverse.next = l1;
l1 = l1.next;
} else {
traverse.next = l2;
l2 = l2.next;
}
traverse = traverse.next;
}
traverse.next = l1 != null ? l1 : l2;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment