以另一个列表的相反顺序创建第二个单链表
Creating a second singly-linked list in reverse order of another list
我需要创建一个函数,它接受一个普通的单链表,并以第一个列表的相反顺序创建另一个列表,新列表中的第一个元素将是原始列表中的最后一个元素,依此类推.
出于某种原因,我的功能只会 returns 对整个新列表一遍又一遍地使用相同的数字。因此,如果我原始列表中的最后一个数字是例如'50',新名单将完全由'50'组成。
这是我的代码,我做错了什么?如果有人想让我 post 整个程序更清楚或上下文给我一个喊。
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;
}
您的代码不可能是正确的,因为它只创建了一个新节点,然后修改了现有节点中的下一个 link。根据您的要求,您必须创建一个新列表,这意味着克隆所有节点并 link 以相反的顺序排列它们。
根据@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;
}
我需要创建一个函数,它接受一个普通的单链表,并以第一个列表的相反顺序创建另一个列表,新列表中的第一个元素将是原始列表中的最后一个元素,依此类推.
出于某种原因,我的功能只会 returns 对整个新列表一遍又一遍地使用相同的数字。因此,如果我原始列表中的最后一个数字是例如'50',新名单将完全由'50'组成。
这是我的代码,我做错了什么?如果有人想让我 post 整个程序更清楚或上下文给我一个喊。
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;
}
您的代码不可能是正确的,因为它只创建了一个新节点,然后修改了现有节点中的下一个 link。根据您的要求,您必须创建一个新列表,这意味着克隆所有节点并 link 以相反的顺序排列它们。
根据@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;
}