如何在不使用“ - >”的情况下将值添加到链接列表中?

时间:2017-02-14 01:21:12

标签: c++

void CommunicationNetwork:: buildNetwork(){

    string citylist [] = {"Phoenix", "Denver", "Dallas", "St. Louis", "Chicago", "Atlanta", "Washington D.C.", "New York", "Boston"};

    head = ("Los Angeles", NULL, NULL);
    City *temp2 = new City;

    City *temp = new City;

    temp=head;

    for(int i=0;i<9;i++){

        temp2->cityName=citylist[i]; //=Pheonix
        temp->next=temp2;            //segmentation fault here
        temp=temp2;
    }
}

City是链接列表的结构。 next指向下一个节点。我收到分段错误,因为我试图取消引用next的NULL temp值。这是我可以考虑将值添加到temp的唯一方法。除了temp2之外,还有另一种方法可以用temp->next= temp2替换NULL吗?

1 个答案:

答案 0 :(得分:0)

这不是实现链接列表的正确方法。看起来应该更像这样:

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(或C ++ 11及更高版本中的std::forward_list),让它为你管理内存:< / p>

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]);
}