【问题标题】:Merge method C++合并方法 C++
【发布时间】:2011-02-16 01:50:37
【问题描述】:

我想编写一个以交替方式将两个列表合并在一起的方法。所以如果我有 list1=(0,1,2,3,4) 和 list2=(5,6,7,8),那么最终的列表应该是 (0,5,1,6,2,7,3 ,8,4)。你有什么想法或提示吗,因为我尝试了很多东西,但都没有意义。

【问题讨论】:

标签: c++


【解决方案1】:

如果您不需要保持原始列表完整无缺,这非常简单。

算法看起来像这样:

  1. 从列表1的头部开始,到第1项(1.1)

  2. 从list 2中挑出对应的item(2.1),将其head改为list 1 head,其prev改为list 1当前item(1.1),将当前item next指针改为2.1,改为1 ' next 指向 1.2 的指针。确保 1.2 prev 现在指向 2.1。

  3. 在每个列表上移动到 1.2 和 2.2,然后重复,直到结束。

【讨论】:

  • 问题是当我们操作和进行这些分配时,我们失去了对 1.2 指针的访问权限并且我们失去了对很多东西的跟踪。
  • 我猜这就是飞碟发明临时变量的原因
【解决方案2】:
// I've been doing Java for a few years now, so my pointers are a bit rusty...
// Forgive pointer errors and focus on concept
/** 
 * @Param list1 the pointer to the head of the first list
 * @Param list2 the pointer to the head of the second list
 * Assumption - list 1 will be able to swallow list 2 without overflowing
 *              handling that is left to OP
 */
void mergeInto(Node *list1, Node *list2) {
    Node curr1 = list1;
    Node curr2 = list2;

    while(curr2 != null) {
        // store after nodes
        Node after1 = curr1.next;
        Node after2 = curr2.next;

        // link curr2 into list1
        curr1.next = curr2;
        curr2.prev = curr1;

        after1.prev = curr2;
        curr2.next = after1;

        // move on to the next in list2
        curr2 = after2;
    }


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-24
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多