从方法获取链接列表中的位置

时间:2017-12-06 22:19:16

标签: c++ linked-list

在这个函数中(我正在处理的一个更大的联系簿程序的一部分),它在链表中显示一个项目,或者在我的情况下显示一个联系人。我想在链接列表中获取此项目的位置,以便删除该联系人并将其添加回链接列表。

void display_contact(std::string first, std::string last)
{
        bool found;

        node *curr = head;
        found = false;

        while (curr != NULL & !found)
        {
            if (curr->firstName == first)
            {
                found = true;
            }
            else if (curr->lastName == last)
            {
                found = true;
            }
            else
            {
                curr = curr->next;
            }

        }
        if (found)
        {
            std::cout << "First Name: " << curr->firstName << "\n";
            std::cout << "Last Name: " << curr->lastName << "\n";
            std::cout << "Phone Number: " << curr->phoneNumber << "\n";
            std::cout << "Editing contacts is coming soon.\n";
        }
        else
        {
            std::cout << "\n" << first << " " << last << " was not found.\n";
        }
}

我现在得到的实际结果只是联系信息(链表中的变量)

1 个答案:

答案 0 :(得分:0)

node *curr = head;
found = false;
int idx = -1;
while (curr != NULL & !found)
{
    idx++;
    ....
 }

如果发现idx具有索引