题目描述

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``````

解法一

Python

``````# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val > l2.val:
l1, l2 = l2, l1
p = l1
while p is not None:
while l2 is not None and (p.next is None or l2.val < p.next.val):
tmp = l2
l2 = l2.next
tmp.next = p.next
p.next = tmp
p = p.next
p = p.next
return l1``````

Java

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val > l2.val) {
ListNode temp = l1;
l1 = l2;
l2 = temp;
}
ListNode p = l1;
while (p != null) {
while ((l2 != null) && ((p.next == null) || (l2.val < p.next.val))) {
ListNode temp = l2;
l2 = l2.next;
temp.next = p.next;
p.next = temp;
p = p.next;
}
p = p.next;
}
return l1;
}
}``````

C++

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
if (l1->val > l2->val) {
ListNode *temp = l1;
l1 = l2;
l2 = temp;
}
ListNode *p = l1;
while (p != nullptr) {
while (l2 != nullptr && (p->next == nullptr || l2->val < p->next->val)) {
ListNode *temp = l2;
l2 = l2->next;
temp->next = p->next;
p->next = temp;
p = p->next;
}
p = p->next;
}
return l1;
}
};``````