Leetcode - Merge Two Sorted Lists
- UID
- 1066743
|
Leetcode - Merge Two Sorted Lists
My code:
/**
* 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 && l2 != null)
return l2;
else if (l1 != null && l2 == null)
return l1;
else if (l1 == null && l2 == null)
return null;
ListNode temp1 = l1;
ListNode temp2 = l2;
ListNode head = null;
if (l1.val <= l2.val) {
head = l1;
temp1 = l1.next;
}
else {
head = l2;
temp2 = l2.next;
}
ListNode temp = head;
ListNode tail = temp;
while (temp1 != null && temp2 != null) {
if (temp1.val <= temp2.val) {
temp.next = temp1;
temp = temp.next;
if (temp1.next == null)
tail = temp1;
temp1 = temp1.next;
}
else {
temp.next = temp2;
temp = temp.next;
if (temp2.next == null)
tail = temp2;
temp2 = temp2.next;
}
}
if (temp1 == null)
tail.next = temp2;
else if (temp2 == null)
tail.next = temp1;
return head;
}
} |
|
|
|
|
|