问题
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