Merge Two Sorted Lists
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.
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode start, runner1, runner2;
if (l1.val <= l2.val) {
start = new ListNode(l1.val);
runner1 = l1.next;
runner2 = l2;
} else {
start = new ListNode(l2.val);
runner1 = l1;
runner2 = l2.next;
}
ListNode result = start;
while (runner1 != null && runner2 != null) {
if (runner1.val <= runner2.val) {
start.next = new ListNode(runner1.val);
runner1 = runner1.next;
} else {
start.next = new ListNode(runner2.val);
runner2 = runner2.next;
}
start = start.next;
}
if (runner1 == null) {
while (runner2 != null) {
start.next = new ListNode(runner2.val);
start = start.next;
runner2 = runner2.next;
}
} else {
while (runner1 != null) {
start.next = new ListNode(runner1.val);
start = start.next;
runner1 = runner1.next;
}
}
return result;
}
}