队列链表未打印其内容



我正在尝试使用链表实现获取队列的输入。问题是队列的内容没有被打印出来。我试着调试,但在函数displayCar中,指针p无论如何都是null。我不知道指针p为NULL的原因是什么。当我试图从carInput功能推送时,是否缺少引用?

#include <iostream>
#include <queue>
using namespace std;
class record
{
public:
string ownerID, plateNumber;
record* next;
};

void push(string ownerID1, string plateNumber1, record **head, record **tail) {
record *n = new record();
n->ownerID = ownerID1;
n->plateNumber = plateNumber1;
n->next = NULL;
if (*head == NULL) {
*head =*tail= n;
}
else {
(*tail)->next = n;
*tail = n;
}
}

void pop(record** head, record** tail) {
record* p = *head;
while (*head != NULL) {
*head = (*head)->next;
free(p);
p = *head;
}
if (*head == NULL)
{
*tail = NULL;
}
}
void carInput(record *head, record *tail) {
char choice = 'Y';
string ownTemp, plateTemp;
while (choice == 'Y') {
cout << "Enter Owner Name: ";
cin >> ownTemp;
cout << "Enter Plate Number: ";
cin >> plateTemp;
push(ownTemp,plateTemp,&head,&tail);
cout << "Press [Y] for next input: ";
cin >> choice;
}

}
void displayCar(record* head, record *tail) {
record* p = head;
cout << "List Of Cars: n";
int i = 1;
while (p!= NULL) {
cout << i << ". Owner Name: " << p->ownerID << endl;
cout << i << ". Plate Number: " << p->plateNumber<< endl;
pop(&head,&tail);
i++;
}
}

void serviceCar(record *head,record*tail) {
record* p = head;
string plateTemp;
int i = 0, time = 0;
char choice = 'Y';

cout << "Enter Plate Number:";
cin >> plateTemp;
while (p!= NULL) {
if (p->plateNumber == plateTemp) {
cout << "There is [" << i << "] car in queue before your turn. Estimated time in queue: " << time;
}
else {
i++;
time = time + 45;
}
pop(&head,&tail);
}
}

int main() {

record* head = NULL;
record*tail = NULL;


cout << ":: Car Record::nn";
carInput(head,tail);
displayCar(head,tail);
serviceCar(head, tail);





}

我不知道当你在C++中时,为什么要用这样的代码来惩罚自己,而且有很多更简单的方法可以做到这一点,但无论如何,我都会通过强调主要问题来提供帮助:

1( 。您必须挣扎的主要原因是,在第一个push中,即使在*head =*tail= n;之后,*head->next仍然是NULL,稍后当您尝试从head迭代时,就像在pop*head = (*head)->next;中所做的那样,您将一无所获。

2( 。如果要执行pop,则应该为每个调用删除一个元素,而不是整个集合,因此需要if而不是while。您有while,每次迭代都使用pop,在pop中也有while,所以请仔细考虑。此外,您应该返回该值以方便地显示它,或者更改在displayCar中尝试coutp的方式。

3( 。当你想显示集合时,你只需要遍历集合,而不是删除所有元素,这会在一次显示后留下空的集合。你只需要迭代并显示它们,而不是删除它们,比如:

record* p = *head;
int i = 0;
while (p != NULL) {
cout << i << ". Owner Name: " << p->ownerID << endl;
cout << i << ". Plate Number: " << p->plateNumber<< endl;
p = p->next;
i++;
}

还有一些其他的要点应该提到,但我认为这足以让代码朝着正确的方向发展——无论如何,我的建议是,试着好好看看简单的链表是如何完成的,然后尝试队列链表,或者只是检查已经写好的示例,然后自己尝试。GeeksForGeeks

您的carInput按值接收指针,修改这些指针对传递给它的指针没有影响。
因此,mainheadtail始终为空
(您通过推送和弹出功能解决了这个问题,但未能在此处应用相同的原理。(

void carInput(record **head, record **tail) {
char choice = 'Y';
string owner, plate;
while (choice == 'Y') {
cout << "Enter Owner Name: ";
cin >> owner;
cout << "Enter Plate Number: ";
cin >> plate;
push(owner, plate, head, tail);
cout << "Press [Y] for next input: ";
cin >> choice;
}
}

您需要将此修复程序与注释中指出的修复程序结合起来。

最新更新