Is this method of making copy of a linked list correct?

大憨熊 提交于 2019-12-08 03:45:39

问题


void InsertAtTail(struct node** headref,int val)
{
    struct node *current,*newnode;
    current=*headref;
    newnode=malloc(sizeof(struct node));

    if(current==NULL)
    {
        newnode->data=val;
        newnode->next=NULL;
        *headref=newnode;
        current=*headref;
    }

    else
    {

        while(current->next!=NULL)
        {
            current=current->next;
        }

        newnode->data=val;
        newnode->next=NULL;
        current->next=newnode;
    }
}

struct node* CopyList(struct node* headref)
{
    struct node* newlist=NULL;
    struct node* current;
    current=headref;


    if(current==NULL)
    {
        newlist=current;
    }

    else
    {
        while(current!=NULL)
        {
            InsertAtTail(&newlist, current->data);
            current=current->next;
        }

    }
    return (newlist);
}

I was going through Stanford's CS101 notes and found code for making a copy of linked list. But it used a pointer to the tail node as well. I have written this code without using that(tail pointer). I am new to linked list. Please tell me if I can proceed this way as well. When I printed the original and copy's addresses, both were different too. I am using c in Xcode.


回答1:


Works correct, though shorter:

void InsertAtTail(struct node** ref,int val)
{
    while (*ref != NULL) {
        ref = &(*ref)->next;
    }
    struct node *newnode = malloc(sizeof(struct node));
    newnode->data=val;
    newnode->next=NULL;
    *ref = newnode;
}

And the list copying should be rewritten: N²/2.



来源:https://stackoverflow.com/questions/18373657/is-this-method-of-making-copy-of-a-linked-list-correct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!