我刚刚完成了创建链接列表的程序,还应该打印出内容。它可以正确编译,看起来可以构成链接列表,但是似乎什么也没打印出来。关于我在这里做错的任何建议吗?
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct DeltaTimerNode
{
int timerInterval;
DeltaTimerNode *next;
DeltaTimerNode(int tempTimeInt, DeltaTimerNode *tempNext = NULL)
{
timerInterval = tempTimeInt;
next = tempNext;
}
};
DeltaTimerNode *deltaTimerList = NULL;
void insert(int deltaTimerValue)
{
deltaTimerList = new DeltaTimerNode (deltaTimerValue, deltaTimerList);
}
int main()
{
int tickTime;
char choice;
vector<int> rawTimers;
//int i = 0; Originally used for tracking something. Moved logic to different function.
do
{
cout<< "Input timer value (not delta timer)." << endl;
cin >> tickTime; //Input regular value of timer, not the delta time. That will be converted automatically.
rawTimers.push_back(tickTime);
//i++;
cout<< "Are there more timer values? Input y for yes, n for no."<<endl;
cin >> choice;
}
while(choice == 'y');
sort (rawTimers.begin(), rawTimers.end());
DeltaTimerNode *deltaTimerList = NULL;
for (int j = 0; j < rawTimers.size(); j++) //for loop populates list.
{
if (j == 0)
{
insert (rawTimers[0]);
}
else
{
insert (rawTimers[j] - rawTimers[j-1]);
}
}
DeltaTimerNode *ptr = deltaTimerList;
while (ptr != NULL)
{
cout << ptr -> timerInterval << " "; //should print out stuff here.
ptr = ptr -> next;
}
return 0;
}
最佳答案
您声明了局部变量deltaTimerList
,并遮盖了全局变量deltaTimerList
。删除有害声明
DeltaTimerNode *deltaTimerList = NULL;
来自
main()
。还要注意,您应该通过
delete
销毁通过new
创建的任何内容。关于c++ - 如何在C++中打印出以下实现的链接列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35930343/