题目:
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解决方案:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode temp = new ListNode(0);
ListNode head = new ListNode(0);
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
head = l1;
l1 = l1.next;
}else {
head = l2;
l2 = l2.next;
}
temp = head;
while (l1 != null) {
if (l2 == null) {
temp.next = l1;
return head;
}
if (l1.val < l2.val) {
temp.next = l1;
l1 = l1.next;
temp = temp.next;
}
else if (l1.val >= l2.val ){
temp.next = l2;
l2 = l2.next;
temp = temp.next;
}
}
if (l2 != null){
temp.next = l2;
}
return head;
}
执行结果:
版权说明:题目来自LeetCode,解决方案原创