代码在c++中,我试着用链表制作货车,每辆车都有一个类型(比如第一类和第二类),代码没有打印货车的详细信息,我试着在货车的插入函数中更改内容,但仍然不能工作。
#include <iostream>
#include <string>
using namespace std;
struct passenger{
string name, surname;
passenger * PNext; // next passenger
}*PFirst = nullptr, *PLast = nullptr;
//wagon
struct wagon{
int SeatNumber;
int WagonQuantity;
string WagonType;
wagon * WNext ;// next wagon
}*WFirst=nullptr, *WLast = nullptr;
//passengers
void InsertWagon(wagon * head, int SNumber, string WType){ // pointer to the first wagon, seat number, wagon type.
head = new wagon();
WFirst -> WNext = head;
if(WFirst == nullptr){
head -> SeatNumber = SNumber;
head ->WagonType = WType;
head = WLast;
WLast -> WNext = nullptr;
}else{
wagon * temp = head;
while(temp -> WNext != nullptr){
temp = temp -> WNext;
}
temp -> WNext = WLast;
}
}
void InsertPassenger(int seat, string type){ // wanted seat, type of the wagon
passenger * NewPassenger = new passenger();
while(type != WFirst -> WagonType){
WFirst = WFirst -> WNext;
}
}
void DisplayWagons(wagon * p){
while(p){
cout << p->WagonType << endl << p->SeatNumber;
p = p-> WNext;
}
}
int main(){
InsertWagon(WFirst, 15, "I");
DisplayWagons(WFirst);
return 0;
}发布于 2022-05-20 16:36:20
指针WFirst最初等于nullptr
struct wagon{
int SeatNumber;
int WagonQuantity;
string WagonType;
wagon * WNext ;// next wagon
}*WFirst=nullptr, *WLast = nullptr;因此,由于使用空指针访问内存,函数InsertWagon立即调用未定义的行为。
void InsertWagon(wagon * head, int SNumber, string WType){ // pointer to the first wagon, seat number, wagon type.
head = new wagon();
WFirst -> WNext = head;
//...或者这个代码片段
head = WLast;
WLast -> WNext = nullptr;也会调用未定义的行为,没有意义。看来你是说
WLast = head;
WLast -> WNext = nullptr; 无论如何,第一个函数参数
void InsertWagon(wagon * head, int SNumber, string WType){不被使用。它的价值立刻被覆盖。当函数处理全局变量时,参数没有意义。把它移开。使用您的方法,函数至少应该声明如下
void InsertWagon( int SNumber, const std::string &WType );请注意,使用全局变量(例如WFirst和WLast )是个坏主意。
如果您想要一个双面单链列表,那么再声明一个包含这些指针的结构。
https://stackoverflow.com/questions/72321899
复制相似问题