Merge _Two_Sorted_Lists

本文介绍了一种合并两个已排序的单链表的方法,并通过Python实现。该算法通过比较两个链表节点的值来合并链表,最终形成一个新的有序链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The main purpose of this article is to complete the merging of two sorted lists.

"""
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
"""
import numpy as np

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

"""单链表"""
class SingleLinkList(object):
    def __init__(self):
        self.__head = None
    """判断链表是否为空"""
    def is_empty(self):
            return self.__head == None
    """链表长度"""
    def length(self):
        # cur初始时指向头节点
        cur = self.__head
        count = 0
        # 尾节点指向None,当未到达尾部时
        while cur != None:
            count += 1
            # 将cur后移一个节点
            cur = cur.next
        return count
    """遍历链表"""
    def travel(self):
        cur = self.__head
        while cur != None:
            print(cur.val, end=" ")
            cur = cur.next
        print("")

    """尾部添加元素"""
    def append(self, val):
        node = ListNode(val)
    # 先判断链表是否为空,若是空链表,则将_head指向新节点
        if self.is_empty():
            self.__head = node
    # 若不为空,则找到尾部,将尾节点的next指向新节点
        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node

class Solution(object):

    def mergeTwoLists(L1,L2):
        """
        :type L1: ListNode
        :type L2: ListNode
        :rtype: ListNode
        """
        head = cur = ListNode(0)

        while L1 and L2:
            if L1.val > L2.val:
                cur.next = L2
                L2 = L2.next
            else:
                cur.next = L1
                L1 = L1.next
            cur = cur.next
        """or 返回第一个为真的值"""
        cur.next = L1 or L2
        return head.next

if __name__=="__main__":
    array1 = sorted(np.random.random_integers(1,15,5))
    array2 = sorted(np.random.random_integers(1,10,5))

    print('array1'+str(array1))
    print('array2'+str(array2))

    L1= SingleLinkList()
    L2= SingleLinkList()

    for each in array1:
        L1.append(each)

    for each in array2:
        L2.append(each)


    sol = Solution
    # print(L1._SingleLinkList__head.val)
    # print(L2._SingleLinkList__head.val)
    L = sol.mergeTwoLists(L1._SingleLinkList__head, L2._SingleLinkList__head)


    L3 = SingleLinkList()
    L3._SingleLinkList__head = L
    L3.travel()

The result of the operation is

                                                         

### 关于排序缓冲区的概念和技术 在数据库和算法上下文中,`Sort Buffer` 是一种用于优化数据处理的技术。它主要用于存储中间状态的数据以便执行高效的排序操作。当内存中的可用空间不足以容纳整个数据集时,可以采用分块策略来管理这些数据[^1]。 #### 排序缓冲区的工作原理 为了实现高效排序,在实际应用中通常会将大数据划分为多个较小的子集(即区块)。每一个区块仅包含原始数据集中的一部分记录,并且可以在有限大小的记忆体内完成局部排序工作。随后通过外部合并的方式把各个已排序好的区块组合成最终完全有序的结果序列[^1]。 以下是具体过程的一个简化描述: 1. 数据被分割为若干个小批次。 2. 每一批次单独利用 sort buffer 进行内部排序。 3. 所有经过初步整理的小批量再经由特定方法如归并排序等手段综合起来形成全局顺序排列。 这种机制不仅适用于单机环境下的大文件处理场景,同时也扩展到了分布式计算框架之中。例如Hadoop MapReduce作业里就有类似的分区汇总流程设计思路存在其中。 另外值得注意的是,在某些情况下如果输入规模超过了预分配给定容量,则可能需要借助磁盘作为辅助储存媒介来进行所谓的out-of-core operations(超出核心之外的操作)[^1]。 ```python def external_merge_sort(data_chunks): """模拟外部分布式排序""" sorted_sublists = [] # 对每个chunk进行独立排序 (假设已经在内存允许范围内) for chunk in data_chunks: sorted_chunk = perform_in_memory_sort(chunk) # 使用sort buffer sorted_sublists.append(sorted_chunk) # 合并所有已经排序过的sublist到一起得到最终结果 final_sorted_list = merge_multiple_lists(*sorted_sublists) return final_sorted_list def perform_in_memory_sort(subset_of_data): """简单表示如何在一个subset上做in-memory sorting.""" subset_of_data.sort() return subset_of_data def merge_two_sorted_lists(list_a,list_b): merged_result=[] i=j=0 while True: if list_a[i]<list_b[j]: merged_result.append(list_a[i]) i+=1 else : merged_result.append(list_b[j]) j +=1 if i>=len(list_a): merged_result.extend(list_b[j:]) break elif j >= len(list_b): merged_result.extend(list_a[i:]) break return merged_result def merge_multiple_lists(*args): current_merged=args[0] for next_to_merge in args[1:]: current_merged=merge_two_sorted_lists(current_merged,next_to_merge ) return current_merged ``` 以上代码片段展示了基本的外部合并排序逻辑,其中包括了针对每一块数据使用 `perform_in_memory_sort()` 函数调用以及最后阶段运用多次两路归并将各片断整合为一体的过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值