代码块

O(1)的空间内合并两个链表

python

class ListNode:

    def __init__(self, x):
        self.val = x
        self.next = None


def merge(l1, l2):
    head = point = ListNode(0)

    while l1 and l2:
        if l1.val <= l2.val:
            point.next = l1
            l1 = l1.next
        else:
            point.next = l2
            l2 = l2.next
        point = point.next

    if l1:
        point.next = l1
    if l2:
        point.next = l2

    return head.next

 C++

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* mergeTwoLists(ListNode *a, ListNode *b) {
    if ((!a) || (!b)) return a ? a : b;
    ListNode head, *tail = &head, *aPtr = a, *bPtr = b;
    while (aPtr && bPtr) {
        if (aPtr->val < bPtr->val) {
            tail->next = aPtr; aPtr = aPtr->next;
        } else {
            tail->next = bPtr; bPtr = bPtr->next;
        }
        tail = tail->next;
    }
    tail->next = (aPtr ? aPtr : bPtr);
    return head.next;
}

 

posted @ 2020-07-02 09:01  r1-12king  阅读(153)  评论(0编辑  收藏  举报