码迷,mamicode.com
首页 > 其他好文 > 详细

代码块

时间:2020-07-02 09:27:37      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:__init__   ini   style   ext   tail   none   val   python   poi   

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;
}

 

代码块

标签:__init__   ini   style   ext   tail   none   val   python   poi   

原文地址:https://www.cnblogs.com/r1-12king/p/13222824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!