题目链接:https://leetcode.com/problems/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.
思路:
easy 。
算法:
-
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
-
ListNode head = null, l, p = l1, q = l2;
-
-
if (p != null && q != null) {
-
if (p.val < q.val) {
-
head = p;
-
p = p.next;
-
} else {
-
head = q;
-
q = q.next;
-
}
-
} else if (p == null) {
-
head = q;
-
return head;
-
} else if (q == null) {
-
head = p;
-
return head;
-
}
-
l = head;
-
-
-
while (p != null && q != null) {
-
if (p.val < q.val) {
-
l.next = p;
-
l = p;
-
p = p.next;
-
} else {
-
l.next = q;
-
l = q;
-
q = q.next;
-
}
-
}
-
-
if (p == null) {
-
l.next = q;
-
} else if (q == null) {
-
l.next = p;
-
}
-
-
return head;
-
}