c++ - 以另一个列表的相反顺序创建第二个单链表

标签 c++ list linked-list reverse singly-linked-list

我需要创建一个函数,它接受一个普通的单链表并以第一个列表的相反顺序创建另一个列表,新列表中的第一个元素将是原始列表中的最后一个元素,依此类推。

出于某种原因,我的函数只会对整个新列表一遍又一遍地返回相同的数字。因此,如果我原始列表中的最后一个数字是例如'50',新名单将完全由'50'组成。

这是我的代码,我做错了什么?如果有人想让我发布整个程序以获得更清晰的信息或上下文,请告诉我。

void invert() {
    node *list1=top,*newlist,*temp,*prev;
    while (list1->next!=NULL) {
        list1=list1->next;
    }
    newlist=new node;
    newlist->num=list1->num;
    newlist->next=NULL;
    if (top2==NULL) {
        top2=newlist;
    }
    else {
        for (temp=top2;temp!=NULL;temp=temp->next) {
            prev=temp;
        }
        prev->next=newlist;
    }
    list1->next=NULL;
}

最佳答案

您的代码不可能是正确的,因为它只创建了一个新节点,然后修改了现有节点中的下一个链接。根据您的要求,您必须创建一个新列表,这意味着克隆所有节点并以相反的顺序链接它们。

根据@user4581301 的建议,我想出了以下办法:

node* invert(node* list)
{
    node* inverted = NULL;
    // run through original in order
    for (node* p = list; p != NULL; p = p->next) 
    {
        // clone the node
        node* newNode = new node(); 
        newNode->num = p->num;
        // and link it so that the predecessor in the original list
        // (which has been processed in the previous iteration) is
        // linked as next node
        newNode->next = inverted;
        inverted = newNode;
    }
    return inverted;
}

关于c++ - 以另一个列表的相反顺序创建第二个单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54641642/

相关文章:

c++ - 密码++ : CFB_Mode_ExternalCipher not working

java - 如何从保存 List<> 对象的文件中反序列化?

c - 使用 malloc 初始化指向结构体的指针

c++ - 如何删除 VS 命令行开关

c++ - C++ 中的循环不再工作

c++ - Microsoft Visual C++ 的两阶段模板实例化的 "broken"究竟是什么?

python - 如何合并列表中的损坏文本并附加到字典中?

python - 列表列表更改意外地反射(reflect)在子列表中

c++ - 对链表打印函数的 undefined reference

c - 在链表中,程序在进入结构体成员时关闭