剑指offer | 合并两个排序的链表 | 14


思路分析

这个其实就是归并排序的归并步骤,只不过是链表的版本

cpp

/**
 * 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) {
                auto dummy = new ListNode(-1);
        auto cur = dummy;
        while(l1 && l2){
            if(l1->val < l2->val){
                cur->next = l1;
                cur = cur->next;
                l1 = l1->next;
            }else{
                cur->next = l2;
                cur = cur->next;
                l2 = l2->next;
            }
        }
        while(l1){
            cur->next = l1;
            cur = cur->next;
            l1 = l1->next;
        }
        while(l2){
            cur->next = l2;
            cur = cur->next;
            l2 = l2->next;
        }

        return dummy->next;
    }
};

python

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = ListNode(-1)
        cur = dummy
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = l1
                cur = cur.next
                l1 = l1.next
            else:
                cur.next = l2
                cur = cur.next
                l2 = l2.next
        while l1:
                cur.next = l1
                cur = cur.next
                l1 = l1.next
        while l2:
                cur.next = l2
                cur = cur.next
                l2 = l2.next
        return dummy.next
原文地址:https://www.cnblogs.com/Rowry/p/14305390.html