我需要创建一个函数,它接受一个普通的单链表并以第一个列表的相反顺序创建另一个列表,新列表中的第一个元素将是原始列表中的最后一个元素,依此类推。
出于某种原因,我的函数只会对整个新列表一遍又一遍地返回相同的数字。因此,如果我原始列表中的最后一个数字是例如'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/