我刚刚完成了制作链表的程序,也应该打印出内容。 它编译正确,似乎可以制作链表,但似乎没有打印出任何东西。 关于我在这里做错了什么的任何建议?
#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
并遮蔽了 gloval 变量deltaTimerList
。删除有害声明
DeltaTimerNode *deltaTimerList = NULL;
从main()
.
另请注意,您应该通过delete
销毁您通过new
创建的任何内容。
首先,您需要删除结构中的默认构造函数,并且不需要insert()函数和全局变量。只需创建一个新节点,并在每次使用节点时将指针指定为新节点即可。我希望你明白这个想法,这应该有效:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct DeltaTimerNode
{
int timerInterval;
DeltaTimerNode *next;
};
int main()
{
int tickTime;
char choice;
vector<int> rawTimers;
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);
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;
DeltaTimerNode* head = &deltaTimerList;
for (int j = 0; j < rawTimers.size(); j++) //for loop populates list.
{
if (j == 0)
{
head->timerInterval = rawTimers[j];
head->next = new DeltaTimerNode();
head = head->next;
}
else
{
head->timerInterval = rawTimers[j] - rawTimers[j - 1];
head->next = new DeltaTimerNode();
head = head->next;
}
}
head = &deltaTimerList;
while (head->next != NULL)
{
cout << head->timerInterval << " "; //should print out stuff here.
head = head->next;
}
return 0;
}