链表数组(5 个队列)



我想实现一个链表数组来创建打印队列;有一个由五个队列组成的数组。每个队列都表示用户打印发送到打印机的作业。

这是我目前拥有的代码:

#include "stdafx.h"
#include <iostream>
using namespace std;
struct node
{
float value;
struct node *next;
};
node *head = NULL;
node* A[5];
int insertNodes(node *head, int value)
{
node *aNode, *Ptr;
aNode = new node;
aNode->value = value;
aNode->next = NULL;
if (head == NULL)
head = aNode;
else
{
Ptr = head;
while (Ptr->next != NULL)
Ptr = Ptr->next;
Ptr->next = Ptr;
}
return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
int num;
for (int i = 0; i < 5; i++)
{
cout << "Insert number";
cin >> num;
A[i] = insertNodes(i, num)
}
return 0;
}

此代码无法按预期工作,因为我无法将"作业"添加到队列中。 我哪里做错了?

您的代码存在许多问题:

  1. 您正在用C++而不是 C 进行编程,因此您应该简单地编写node *next而不是struct node *next

  2. 您的insertNodes函数返回指向列表头部的指针,因此您需要返回node*,而不是int

  3. 当您插入到具有现有标题的列表中时,您永远不会插入该项目。你必须做Ptr->next = aNode,而不是Ptr->next = Ptr

  4. 在你的主函数中,你应该传递一个指向列表头部的指针来insertNodes,但实际上你传递它一个int。相反,请尝试A[i] = insertNodes(A[i], num)

  5. 您将float存储在列表节点中,但输入int- 这真的需要吗?

但是,由于您处于C++,因此通过依赖标准库已经提供的内容,您可能可以完全避免大多数这些陷阱。

只需#include <deque>,您就可以使用std::deque(adouble-e ndedqueue( 提供的所有内容,包括push_back末尾添加元素,front访问第一个元素,pop_front删除它 - 一个真正的队列,不需要自定义链表:

#include "stdafx.h"
#include <deque>
#include <vector>
#include <iostream>
std::vector<std::deque<float>> A {5};
int _tmain(int argc, _TCHAR* argv[])
{
float input;
for (int i = 0; i < 5; i++)
{
std::cout << "Insert number: ";
std::cin >> input;
A[i].push_back(input);
}
return 0;
}

最新更新