正在链表拷贝正确的这种方法吗? [英] Is this method of making copy of a linked list correct?
本文介绍了正在链表拷贝正确的这种方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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);
}
我所经历的斯坦福大学的CS101笔记,发现code制作链表的副本。但所使用的指针的尾节点为好。我写了这个code,而不使用(尾指针)。我是新来的链接列表。请告诉我,如果我可以继续这种方式为好。当我打印的原件及复印件的地址,两人都不同。我正在使用X code C。
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.
推荐答案
作品不正,虽短:
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;
}
和列表复制应该改写。N²/ 2
And the list copying should be rewritten: N²/2.
这篇关于正在链表拷贝正确的这种方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文