代码块
Posted r1-12king
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代码块相关的知识,希望对你有一定的参考价值。
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; }
以上是关于代码块的主要内容,如果未能解决你的问题,请参考以下文章