これは、リンクリストを実装する正しい方法ではありません。その後、
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]);
}
そして:あなたはそれのためにすべての時間を狩りする必要はありませんので、その後、ヘッドノードと一緒にテール・ノードを思い出し恩恵を受ける
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;
}
}
:それはより次のようになりますあなたはそれが働いていたら、手動でリストを捨てると、(C++ 11以降またはstd::forward_list
)std::list
を使用する代わりに、それはあなたのためのメモリを管理しましょう:
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"という行でtempに指されていませんか? – user7554736
'a-> b'は'(* a).b'のショートカットですので、 ' - >'を使わずにコードを機械的に書き換えることができます。 – dasblinkenlight