所以我有一些列表(HeadFirstCl,HeadNoSm,HeadSm)我想连接并制作一个大列表(HeadByPlace),而其他列表仍然存在。我的问题是为什么我的ConnectLists功能不起作用?
#include <iostream>
#include <string>
using namespace std;
struct Item {
string naprav;
string chasizl;
string chaskac;
int termizl;
int termkac;
char fime[5];
int mqsto;
Item *NextByPlace;
};
typedef Item *Point;
Point HeadByPlace, HeadFirstCl, HeadNoSm, HeadSm;
void ConnectLists(Point &P, Point A) {
while (A) {
if (P->NextByPlace == NULL)
P->NextByPlace = A;
P = P->NextByPlace;
}
}
void PrintOut(Point P) {
while (P) {
cout << P->fime<<endl;
cout << P->chasizl << endl;
cout << P->chaskac << endl;
cout << P->mqsto << endl;
cout << P->naprav << endl;
cout << P->termizl << endl;
cout << P->termkac << endl;
P = P->NextByPlace;
}
}
void Create(Point &Head, int i) {
Point Last, P;
Last = NULL;
P = new Item;
P->mqsto = i;
cout << "Enter destination" << endl;
cin >> P->naprav;
cout << "Enter departure HOUR" << endl;
cin >> P->chasizl;
cout << "Enter arrival HOUR" << endl;
cin >> P->chaskac;
cout << "Enter # of leaving terminal" << endl;
cin >> P->termizl;
cout << "Enter # of entering terminal" << endl;
cin >> P->termkac;
cout << "Last name of traveler" << endl;
cin >> P->fime;
P->NextByPlace = NULL;
if (Head == NULL) {
Head = P;
} else {
Last->NextByPlace = P;
}
Last = P;
}
void Delete(char name[], Point &Head) {
Point Pprev, P;
P = new Item;
Pprev = new Item;
cin >> name;
while (Head) {
if (strcmp(Head->fime, name) == 1) {
Pprev = P->NextByPlace;
*P = *Pprev;
delete Pprev;
}
}
}
void main() {
char ch;
HeadByPlace = NULL;
HeadFirstCl = NULL;
HeadNoSm = NULL;
HeadSm = NULL;
int i;
cout << "New element? (Y/N)? : ";
cin >> ch;
while (ch == 'Y' || ch == 'y') {
cout << "Enter seat #: ";
cin >> i;
if (i < 7) Create(HeadFirstCl,i);
else if (i > 7 && i < 25) Create(HeadNoSm,i);
else if (i > 25) Create(HeadSm,i);
cout << " New element? (Y/N) ?: ";
cin >> ch;
}
ConnectLists(HeadByPlace, HeadFirstCl);
ConnectLists(HeadByPlace, HeadNoSm);
ConnectLists(HeadByPlace, HeadSm);
PrintOut(HeadByPlace);
system("pause");
}
答案 0 :(得分:0)
我想我发现了你的一些问题。您的连接列表功能有一个主要问题,您的while循环永远不会终止。在C ++中,如果指针不为null,则从指针到bool的隐式转换返回true,如果指针为null,则返回false。你的循环无限地检查以查看A是否为空。显然,如果你给函数一个空指针,它就不会做任何事情,但是如果给它一个有效的A指针,它将永远循环,因为A在函数中没有被改变。这是一个简单的功能,实际上可以合并您的列表而不会出现此问题:
void ConnectLists(Point P, Point A) {
while (P->NextByPlace != nullptr) {
P = P->NextByPlace;
}
P->NextByPlace = A;
}
此函数循环直到列表的末尾,然后将A添加到结尾。请注意,对于A或P为空的情况,它不会进行任何错误处理。如果你用这个替换你的功能,它会按你的要求做。
您提供的代码也存在非常基本的问题。如果您创建多个相同类型的条目,则您的create function会出现段错误。此外,您的测试用例存在缺陷。每次调用时,您都会通过connectLists函数将指针HeadByPlace传递给P. HeadByPlace为null,因此尝试访问其任何值(例如nextByPlace)会导致分段错误。如果你想确保我提供的connectLists函数的代码工作,初始化每个列表类型之一(HeadFirstCl,HeadNoSM和HeadSM)并尝试连接它们,或者只是为HeadByPlace分配内存。
另外,我有一条未经请求的建议。您可能需要查看C ++ STL容器:http://www.cplusplus.com/reference/stl/。我认为其中一些数据结构,例如矢量或列表,可能对您有用。