这是一个链接列表:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Arrival
{
string arrAddress;
double distance;
string roadCategory;
struct Arrival* next;
};
class ArrivalList
{
private:
struct Arrival* head;
public:
bool addArrival(string oneAddress, double distance, string roadCategory);
};
bool ArrivalList::addArrival(string oneAddress, double distance, string roadCategory)
{
Arrival* temp;
Arrival* current=new Arrival();
current=head;
temp=new Arrival();
temp->arrAddress=oneAddress;
temp->distance=distance;
temp->roadCategory=roadCategory;
int f=0;
while(1)
{
if(current==NULL)
{
temp->next=NULL;
head=temp;
f=1;
break;
}
else if(oneAddress>=current->arrAddress && oneAddress<current->next->arrAddress)
{
temp->next=current->next;
current->next=temp;
f=1;
break;
}
else
{
current=current->next;
}
}
cout<<head->arrAddress;
if(f)
{
return true;
}
else
{
return false;
}
}
int main()
{
ArrivalList li;
li.addArrival("jjjjj",0.8999,"I");
li.addArrival("aaaaa",0.888,"k");
}
我希望 head 的值在对函数 addArrival 的多次调用中保持不变。但它正在变化。我想从“当前”值开始循环,该值应该是第一次调用后的 head 值,但它正在变化并且我想每次都从 NULL 开始。
我希望每次调用该函数时,它都应该获取更新后的 head 的值并开始循环,但在第一次调用后该值不会保存到 head 中。
您的
ArrivalList
类没有初始化其 head
成员,也没有在使用完列表后释放列表,从而泄漏了节点。
而且,您的
addArrival()
方法还有其他几个问题,包括:
尝试更多类似这样的事情:
#include <iostream>
#include <string>
using namespace std;
class ArrivalList
{
private:
struct Arrival
{
string arrAddress;
double distance;
string roadCategory;
Arrival* next;
};
Arrival* head;
ArrivalList(const ArrivalList&) {}
ArrivalList& operator=(const ArrivalList&) { return *this; }
public:
ArrivalList();
~ArrivalList();
bool addArrival(string oneAddress, double distance, string roadCategory);
};
ArrivalList::ArrivalList() : head(NULL) {}
ArrivalList::~ArrivalList()
{
Arrival* current = head;
while (current)
{
Arrival* temp = current->next;
delete current;
current = temp;
}
}
bool ArrivalList::addArrival(string oneAddress, double distance, string roadCategory)
{
Arrival** current = &head;
while ((*current != NULL) && (oneAddress >= (*current)->arrAddress))
current = &((*current)->next);
Arrival* temp = new Arrival;
temp->arrAddress = oneAddress;
temp->distance = distance;
temp->roadCategory = roadCategory;
temp->next = *current;
*current = temp;
cout << head->arrAddress;
return true;
}