所以对于我的程序,我们使用的是单链表,我很难找到记录。例如,我们对两张评分为5的唱片进行了硬编码。当我们第一次启动我的程序并搜索它们时,两个记录都会显示,但当我们输入一个具有不同评级的新记录时,它会显示未找到评级或未找到地址。我们的代码有什么问题?
附言:顺便说一句,这是一个集体作业,我的同伴做了这个,所以我只是想办法解决这个问题。。。
struct tutor
{
int tutorid, rate;
string tutoraddress;
tutor* next;
};
class record
{
public:
//head as first in node
tutor* head;
tutor* tail;
//Get size of node
int getSize;
//Constructor to flush and renew the value of node to null, and size to 0
record()
{
this->head = NULL;
this->tail = NULL;
this->getSize = 0;
}
void exist()
{
tutor* n = new tutor;
//First
n->tutorid = 1;
n->tutoraddress = "Puchong";
n->rate = 5;
n->next = NULL;
if (head == NULL)
{
head = n;
}
else
{
tail = head;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = n;
}
getSize++;
}
void exist1()
{
tutor* n = new tutor;
//Second
n->tutorid = 2;
n->tutoraddress = "Puchong";
n->rate = 5;
n->next = NULL;
if (head == NULL)
{
head = n;
}
else
{
tail = head;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = n;
}
getSize++;
}
int find()
{
//create n node and assign to head
//then traverse to end of list to find the
//search value
int ch = 0;
int rating = 0;
int id = 0;
string address;
while (true)
{
cout << "n1>Find IDn";
cout << "2>Find ratingn";
cout << "3>Find addressn";
cout << "4>Quitn";
cout << "Select menu: ";
cin >> ch;
if (ch == 1)
{
cout << "nMenu selected: " << ch << "n";
cout << "Enter ID: ";
cin >> id;
tutor* n = head;
while (n != NULL)
{
if (n->tutorid == id)
{
cout << "nID: " << n->tutorid << "n";
system("pause");
return true;
}
else
{
n = n->next;
}
}
cout << "nID not foundn";
system("pause");
return false;
}
else if (ch == 2)
{
cout << "nMenu selected: " << ch << "n";
cout << "Enter rating: ";
cin >> rating;
tutor* n = head;
while (n != NULL)
{
if (n->rate == rating)
{
cout << "nID: " << n->tutorid << "n";
n = n->next;
}
else
{
n = n->next;
cout << "nRate not foundn";
break;
}
}
}
else if (ch == 3)
{
cout << "nMenu selected: " << ch << "n";
cout << "Enter address: ";
cin >> address;
tutor* n = head;
while (n != NULL)
{
if (n->tutoraddress == address)
{
cout << "nID: " << n->tutorid << "n";
n = n->next;
}
else
{
n = n->next;
cout << "nAddress not foundn";
break;
}
}
}
else
{
cout << "nEndn";
system("pause");
break;
}
}
}
}
要回答有关搜索链表的问题,下面是一个通过tutoraddress
:搜索列表的示例函数
tutor * record::find_by_tutor_address(const std::string& key)
{
tutor * p_node = head;
while (p_node != nullptr)
{
if (p_node->tutoraddress == key)
{
break;
}
p_node = p_node->next;
}
return p_node;
}
通过其他字段进行搜索可以使用类似的功能。
基本过程是从头部节点开始,并遵循链接,直到找到节点。如果找不到键,函数将返回nullptr
,或者它将返回一个指向包含键的节点的指针。