【问题标题】:Union of a sorted linked list algorithm排序链表算法的并集
【发布时间】:2015-12-19 21:19:52
【问题描述】:

这是我已经完成的第一部分:

让 A 和 B 成为排序数组,其中 A 的所有元素都不同,B 的所有元素都不同(尽管元素可以同时出现在 A 和 B 中)。设计一个 O(n) 算法,该算法生成一个有序数组 C,其中包含 A 和 B 的所有元素,且不重复。例如,如果 A = [1, 2, 5, 7] 且 B = [2, 5, 10],则 C = [1, 2, 5, 7, 10]。

但我坚持这部分与列表有关:

解决 A 和 B 是链表的情况。

我的代码:

    Merge(A,B,C)
     i=0;
     j=0;
     k=0;
     while (i < A.length && j < B.length)
          if (A.content <= B.content)
               C.content = A.content
               k = k + 1; i = i + 1

【问题讨论】:

    标签: algorithm linked-list


    【解决方案1】:

    您的算法不完整:它没有告诉A.content &gt; B.content 时要做什么。该方法与用于合并两个已排序集合的著名算法几乎相同,只是当两个项目相等时,您推进两个集合。

    使用链表不会改变算法,因为在这两种情况下,您都对每个集合中的单个“头”元素进行操作。

    merge-lists(list a, list b) -> list c
        while !a.at-end && !b.at-end
            if a.head < b.head
                c.add( a.head )
                a.move-next
            else if a.head > b.head
                c.add( b.head )
                b.move-next
            else // it means that a.head == b.head
                c.add( a.head )
                a.move-next
                b.move-next
            end
        while !a.at-end
            c.add( a.head )
            a.move-next
        while !b.at-end
            c.add( b.head )
            b.move-next
    

    【讨论】:

    • 谢谢 标题是什么内容
    • @EmmanuelYohannes 这是链表在当前迭代点的元素。
    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 2017-05-11
    • 1970-01-01
    • 2020-05-24
    • 2018-05-22
    • 2018-07-26
    • 2010-12-04
    相关资源
    最近更新 更多