用c复制一个链表

时间:2021-06-08 07:22:08
typedef struct slist *LInt;

typedef struct slist{

int value;
LInt prox;
}Node;

LInt clone2(LInt l){

LInt nova=NULL,aux2=NULL;
while(l){
    aux2=nova;
    nova=(LInt)malloc(sizeof(Node));
    nova->value=l->value;
    nova->prox=aux2;
    l=l->prox;
    }
return nova;
}

This function is supposed to copy a linked list, but this way, when I call the function to print it on screen, the list comes up reversed... Any help or tip? Thank you in advance!

这个函数应该复制一个链表,但是这样,当我调用这个函数在屏幕上打印它时,这个链表就会反过来显示出来……任何帮助或建议吗?提前谢谢你!

2 个解决方案

#1


3  

you have nova->prox=aux2; where aux2 is the previous node....thus, you are actually pointing backwards in the linked list.

你有新星- > prox = aux2;上一节点.... aux2在哪里因此,您实际上是在链接列表中向后指向。

Pls look at these links for correct logic:

请看看这些链接的正确逻辑:

Coding a function to copy a linked-list in C++

编写一个函数来复制c++中的链表

Adapted @templatetypedef's answer from How do you copy a linked list into another list?

改编@templatetypedef的答案,从如何将链接列表复制到另一个列表中?

LInt Clone(LInt l) {
if (l == NULL) return NULL;

LInt result = (LInt)malloc(sizeof(Node));
result->value = l->value;
result->prox = Clone(l->next);
return result;
}

#2


0  

LInt clone2(LInt l){
    LInt ret=NULL;
    LInt nova, aux2 = NULL;
    while(l){
        nova=(LInt)malloc(sizeof(Node));
        if(!ret) ret = nova;
        if(aux2) aux2->prox = nova;
        nova->value=l->value;
        nova->prox = NULL;
        aux2 = nova;
        l=l->prox;
    }
    return ret;
}

#1


3  

you have nova->prox=aux2; where aux2 is the previous node....thus, you are actually pointing backwards in the linked list.

你有新星- > prox = aux2;上一节点.... aux2在哪里因此,您实际上是在链接列表中向后指向。

Pls look at these links for correct logic:

请看看这些链接的正确逻辑:

Coding a function to copy a linked-list in C++

编写一个函数来复制c++中的链表

Adapted @templatetypedef's answer from How do you copy a linked list into another list?

改编@templatetypedef的答案,从如何将链接列表复制到另一个列表中?

LInt Clone(LInt l) {
if (l == NULL) return NULL;

LInt result = (LInt)malloc(sizeof(Node));
result->value = l->value;
result->prox = Clone(l->next);
return result;
}

#2


0  

LInt clone2(LInt l){
    LInt ret=NULL;
    LInt nova, aux2 = NULL;
    while(l){
        nova=(LInt)malloc(sizeof(Node));
        if(!ret) ret = nova;
        if(aux2) aux2->prox = nova;
        nova->value=l->value;
        nova->prox = NULL;
        aux2 = nova;
        l=l->prox;
    }
    return ret;
}