C++ Can';t在执行反向链表功能后,保持我的链表的完整性
我试图保持我的原始链表(“开始”节点变量位于我的类对象下的头文件中)不变,当通过这个函数输出我已经在“开始”中以相反顺序存储的链表时。该函数工作正常,但在while循环中循环一次后,我的原始链表会变成一系列无休止的指针,反复指向数字11和21(例如,原始列表包含11、21、35、4……等数字,但在while循环中循环一次后,它会转到11、21、11、21……等等)。调试程序时,我可以确定发生这种情况的时间点是在我将调试光标从以下位置移动时:C++ Can';t在执行反向链表功能后,保持我的链表的完整性,c++,pointers,C++,Pointers,我试图保持我的原始链表(“开始”节点变量位于我的类对象下的头文件中)不变,当通过这个函数输出我已经在“开始”中以相反顺序存储的链表时。该函数工作正常,但在while循环中循环一次后,我的原始链表会变成一系列无休止的指针,反复指向数字11和21(例如,原始列表包含11、21、35、4……等数字,但在while循环中循环一次后,它会转到11、21、11、21……等等)。调试程序时,我可以确定发生这种情况的时间点是在我将调试光标从以下位置移动时: next->link = tempStart;
next->link = tempStart;
到
我似乎无法找到一个解决办法或解释这种情况。如果有人碰巧知道如何解决这个问题,我非常想听听你的意见。多谢各位
void IntegerListClass::OutputReverseList(ofstream& fout)
{
int index;
nodePtr tempStart = start;
nodePtr next;
nodePtr current = NULL;
if (start == NULL)
{
return;
}
current = start;
current = current->link;
while (current != NULL)
{
next = current;
current = current->link;
next->link = tempStart;
tempStart = next;
}
current = tempStart;
for (index = 0; index <= numberInList - 1; index++)
{
if (index % 5 == 0)
{
fout << endl;
}
fout << setw(10) << current->data.number;
current = current->link;
}
请为您提供
nodePtr
的代码,如果您没有更新“开始”,则在反转列表后,您希望如何保存反转链接列表的新开始,以便您第二次调用此功能?不仅如此,在反转列表后,还需要设置start->link=nullptr,这是原始的start,因为它现在是反转列表中的最后一个元素;class IntegerListClass{private:nodePtr start;只需编辑您的初始帖子。请在帖子下查找小的编辑链接。@SamVarshavchik我不打算再次调用该函数。反向链接列表的新开始保存在'current=tempStart;'
void IntegerListClass::OutputReverseList(ofstream& fout)
{
int index;
nodePtr tempStart = start;
nodePtr next;
nodePtr current = NULL;
if (start == NULL)
{
return;
}
current = start;
current = current->link;
while (current != NULL)
{
next = current;
current = current->link;
next->link = tempStart;
tempStart = next;
}
current = tempStart;
for (index = 0; index <= numberInList - 1; index++)
{
if (index % 5 == 0)
{
fout << endl;
}
fout << setw(10) << current->data.number;
current = current->link;
}
#ifndef IntegerListClass_h
#define IntegerListClass_h
#include "Standards.h"
//Create a type for the data members
struct nodeType
{
int number;
};
//Create a node with a pointer to set for the link node
struct node
{
nodeType data;
node* link;
};
//Create a type definition, which is a pointer to the node
typedef node* nodePtr;
class IntegerListClass
{
private:
nodePtr start;