Skip to content

Instantly share code, notes, and snippets.

@the-fejw
Created January 28, 2015 01:11
Show Gist options
  • Save the-fejw/26dd79b3ad47a424f320 to your computer and use it in GitHub Desktop.
Save the-fejw/26dd79b3ad47a424f320 to your computer and use it in GitHub Desktop.
/**
* 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) {
ListNode head = null;
ListNode current = head;
int count = 0;
while (l1 != null || l2 != null) {
ListNode node = new ListNode(0);
count++;
if (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
node.val = l1.val;
l1 = l1.next;
} else {
node.val = l2.val;
l2 = l2.next;
}
} else if (l1 != null) {
node.val = l1.val;
l1 = l1.next;
} else {
node.val = l2.val;
l2 = l2.next;
}
if (count == 1) {
head = node;
current = node;
} else {
current.next.val = node.val;
current = current.next;
}
current.next = new ListNode(0);
}
if (current != null)
current.next = null;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment