难度: Easy
原题链接:https://leetcode.com/problems/merge-two-sorted-lists/description/
合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
dummy = cur = ListNode(-1)
# 遍历两个链表,每次比较链表头的大小,每次让较小值添加到 dummy 的后面,并且让较小值所在的链表后移一位
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
# 会出现一条链表遍历完,另外一条链表没遍历完的情况,需要将没遍历的链表添加到结果链表中
cur.next = l1 if l1 else l2
return dummy.next
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode prev = result;
// 遍历两个链表,每次比较链表头的大小,每次让较小值添加到 dummy 的后面,并且让较小值所在的链表后移一位
while (l1!= null && l2!= null) {
if (l1.val >= l2.val) {
prev.next = l2;
l2 = l2.next;
} else {
prev.next = l1;
l1 = l1.next;
}
prev = prev.next;
}
// 会出现一条链表遍历完,另外一条链表没遍历完的情况,需要将没遍历的链表添加到结果链表中
if (l1 != null) {
prev.next = l1;
}
if (l2 != null) {
prev.next = l2;
}
return result.next;
}
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* result = new ListNode(0);
ListNode* prev = result;
// 遍历两个链表,每次比较链表头的大小,每次让较小值添加到 dummy 的后面,并且让较小值所在的链表后移一位
while (l1!= NULL && l2!= NULL) {
if (l1->val >= l2->val) {
prev->next = l2;
l2 = l2->next;
} else {
prev->next = l1;
l1 = l1->next;
}
prev = prev->next;
}
// 会出现一条链表遍历完,另外一条链表没遍历完的情况,需要将没遍历的链表添加到结果链表中
if (l1 != NULL) {
prev->next = l1;
}
if (l2 != NULL) {
prev->next = l2;
}
return result->next;
}
};