首页 > 解决方案 > 如何合并两个双向链表(访问下一个链接)

问题描述

我正在尝试合并两个双向链表。我已经创建了一个以正确顺序插入新节点的函数。参数由我的教授设置,所以我无法更改。我能够将第一项添加到 List1 但无法再添加。

我在尝试继续遍历 List2 并向 List1 添加更多项目时遇到错误。我尝试过递归和 do while 循环。在尝试使用 do-while 循环时

struct nodeType{
int info;
nodeType *next;
nodeType *back;
};

class OrderedDoublyLinkedList{
public:
    //Insert x in appropriate place in the list to keep it 
    sorted
    void insertNode(int x);
    void mergeLists(OrderedDoublyLinkedList &List1, 
    OrderedDoublyLinkedList &List2);

private:
    int count;
    nodeType *first;
    nodeType *last;
};

void 
OrderedDoublyLinkedList::mergeLists(OrderedDoublyLinkedList 
&List1, OrderedDoublyLinkedList &List2){

//First Technique
do{
    List1.insertNode(List2.first->info);
    List2.first->next; //Error: Expresion result unused
}
while(List2.first!=NULL)

//Second Technique
while(List2.first!=NULL)
    List1.insertNode(List2.first->info);
    mergeLists(&List1, &List2.first->next);
//If I try to use this it says cannot bind to a temporary of 
type

我需要帮助访问下一个节点以将其余信息添加到 List1。

标签: c++linked-listdoubly-linked-list

解决方案


看起来你只需要一个简单的 while 循环

nodeType* n = List2.first;
while (n != NULL)
{
    List1.insertNode(n->info);
    n = n->next;
}

虽然我仍然担心这是否是一个可以接受的解决方案。你说你需要搬进 List2List1这不是这段代码的作用,这段代码复制 List2List1List2不受这段代码的影响。


推荐阅读