Неверный способ реализации связанного списка. Это должно выглядеть примерно так:
private:
City *head;
CommunicationNetwork::CommunicationNetwork()
: head(NULL)
{
}
CommunicationNetwork::~CommunicationNetwork()
{
City *temp = head;
while (temp)
{
City *next = temp->next;
delete temp;
temp = next;
}
}
void CommunicationNetwork::buildNetwork()
{
std::string citylist [] = {"Los Angeles", "Phoenix", "Denver", "Dallas", "St. Louis", "Chicago", "Atlanta", "Washington D.C.", "New York", "Boston"};
// find the last node in the list...
City *last = NULL;
if (head)
{
last = head;
while (last->next)
last = last->next;
}
// add the cities to the end of the list...
for(int i = 0; i < 10; ++i)
{
City *temp = new City;
temp->cityName = citylist[i];
temp->next = NULL;
if (!head) head = temp;
if (last) last->next = temp;
last = temp;
}
}
Каких бы то выгода от поминания хвоста узла рядом с узлом головки, так что вам не придется охотиться за это каждый раз, когда:
private:
City *head, *tail;
CommunicationNetwork::CommunicationNetwork()
: head(NULL), tail(NULL)
{
}
CommunicationNetwork::~CommunicationNetwork()
{
City *temp = head;
while (temp)
{
City *next = temp->next;
delete temp;
temp = next;
}
}
void CommunicationNetwork::addCity(const std::string &cityName)
{
City *temp = new City;
temp->cityName = citylist[i];
temp->next = NULL;
if (!head) head = temp;
if (tail) tail->next = temp;
tail = temp;
}
void CommunicationNetwork::buildNetwork()
{
std::string citylist [] = {"Los Angeles", "Phoenix", "Denver", "Dallas", "St. Louis", "Chicago", "Atlanta", "Washington D.C.", "New York", "Boston"};
for(int i = 0; i < 10; ++i)
addCity(citylist[i]);
}
А потом после того, как вы его работать, выбросить ручной список и использовать std::list
(или std::forward_list
в C++ 11 и позже), а, пусть это управление памятью для вас:
private:
std::list<std::string> cities;
void CommunicationNetwork::addCity(const string &cityName)
{
cities.push_back(cityName);
}
void CommunicationNetwork::buildNetwork()
{
string citylist [] = {"Los Angeles", "Phoenix", "Denver", "Dallas", "St. Louis", "Chicago", "Atlanta", "Washington D.C.", "New York", "Boston"};
for(int i = 0; i < 10; ++i)
addCity(citylist[i]);
}
вы должны переместить «temp2 = новый город "внутри цикла и точку головы до temp1. – Mike
Разве голова не указана на температуру с линией «temp = head»? – user7554736
'a-> b' является ярлыком для' (* a) .b', поэтому вы можете механически переписать свой код без '->'. – dasblinkenlight