【发布时间】:2021-11-22 21:56:48
【问题描述】:
此函数的要求:如果全名(名字和姓氏)不等于当前列表中的任何全名,则添加它并返回true。应根据姓氏添加元素。具有相同姓氏的元素应根据 他们的名字。否则,不更改列表并返回 false(表示该名称已在列表中)。
//this function add nodes to the list
//return true if fullname isn't in the list. Else return false if fullname is in the list.
//should be added according to last name.
bool OnlineDating::makeMatch(const std::string& firstName, const std::string& lastName, const OnlineType& value)
{
Node* p = head;
//are these nodes already set to firstName and lastName in this function
Node first;
Node last;
Node* temp = nullptr;
//if the list is empty just insert the fullname and value to the list
if (p == nullptr) {
//add values to the empty list
insertToRear(firstName, lastName, value);
return true;
}
else {
// so this loop is to check if fullname is in the list but first sort in alphebetial order
//sure its added in alphebetical order
//traverse the list after knowing where head is
while (p != nullptr) {
//checking to make sure theres at least another node in the list
if (p->next != nullptr) {
//its not going through ig loop?
//these are used to check and alphebetically selected names
if (p->last > p->next->last) {
insertToRear(p->first, p->last, p->value);
p->next = temp;
return true;
}
else if (p->next->last > p->last) {
insertToRear(p->first, p->last, p->value);
p->next = temp;
return true;
}
//check if full name is already in the list
if (p->last == p->next->last) {
insertToRear(p->first, p->last, p->value);
p->next = temp;
return true;
}
else if (p->first > p->next->first) {
insertToRear(p->first, p->last, p->value);
p->next = temp;
return true;
}
else {
//returns false if it passes through these checks
return false;
}
}
p = p->next;
}
}
}
这是我的 main.cpp
int main()
{
OnlineDating clippersGonnaClip;
clippersGonnaClip.makeMatch("Kawhi", "Leonard", 2);
clippersGonnaClip.makeMatch("Paul", "George", 13);
clippersGonnaClip.makeMatch("Ivica", "Zubac", 40);
clippersGonnaClip.makeMatch("Reggie", "Jackson", 1);
clippersGonnaClip.makeMatch("Patrick", "Beverley", 21);
for (int n = 0; n < clippersGonnaClip.howManyMatches(); n++) {
string first;
string last;
int val;
clippersGonnaClip.confirmMatch(n, first, last, val);
cout << first << " " << last << " " << val << endl;
}
return 0;
}
老实说,我只想创建一个指向每个节点的 ptr。只要该节点不指向 nullptr 就进行检查,并按字母顺序对 LinkedList 进行排序。最后使用我的 *temp 将节点链接在一起。为什么每次编译时它都不让我通过 if 语句我得到一个负数?除了这个 makeMatch(...) 之外,其他所有函数都适用于这个程序。
【问题讨论】:
-
开始更简单:首先创建您的列表并确保所有节点都在其中。然后创建一个函数来交换两个节点,并针对多种情况进行测试(两个第一个节点,两个最后一个节点,两个中间节点)。然后就可以开始看排序了。
-
或者,你知道,使用标准 C++ 容器(最好是
std::vector)和std::sort。 -
列表不应该已经排序了吗?如果列表为空,您只使用
firstName和lastName? -
使用向量是有道理的,但我只能使用数据结构来完成这项任务,并且仅限于他提供的模板。艾伦,我希望列表按字母顺序排序。
-
如果您只在正确位置插入排序列表,那么列表将始终被排序。对链表进行排序是一场噩梦,通常的做法是新建一个链表并使用插入排序
标签: c++ class append structure project