gpt4 book ai didi

c++ - 打印链接列表

转载 作者:行者123 更新时间:2023-12-02 10:39:11 24 4
gpt4 key购买 nike

给定节点的名称,此函数应搜索链接列表。如果在其内部找到,则返回指向该节点的指针,否则返回null。注意:我确定我已经成功编写了此函数。

// getNode

Node *LinkedList::getNode(string name)
{
Node *temp = head;
while (temp != NULL)
{
if (temp->name.compare(name) == 0)
return temp;
temp = temp->next;
}
return NULL;
}

给定一个节点,此函数在屏幕上打印:teamName(winScore-loseScore)。例如:UCLA(25-13)或Texas A&M(31-25)。注意:我确定我已经成功编写了此函数。
// printNode

void LinkedList::printNode(Node *node)
{
if (node == NULL)
return;
else {
cout << node->name << "(" << node->winScore;
cout << "-" << node->loseScore << ")";
}
}

给定一个团队名称,该功能应该以以下格式一张一张地打印其邻接列表中的所有节点(注意:以下仅是一个示例!)这就是我认为错了的地方。
Missouri University beat: New Mexico(52-23), Salisbury (48-31), Virginia (34-9)

void LinkedList::printList(string name)
{
if (head == NULL)
cout << "\n Empty list" << endl;
else {

Node *temp = head;
while (temp != NULL)
{
cout << temp->name << " beat: " << temp->name << endl; // Is this right?
temp = temp->next;
}
}
}

最佳答案

我猜这很接近您想要的:

void LinkedList::printList(string name)
{
// find the node for the name you supply
// (or else I don't understand why 'name' is supplied to this function)

Node *temp = getNode(name);

if (temp) { // node with name found
if (temp->next) { // there's at least one adjacent node
cout << temp->name << " beat: ";
while ((temp = temp->next) != nullptr) {
printNode(temp);
if (temp->next) cout << ", ";
};
cout << "\n";
} else { // no adjacent nodes
cout << temp->name << " did not beat anyone\n";
}
}
}

关于c++ - 打印链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53489306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com