链表数组(5 个队列)
Array Of Linked Lists (5 Queues)
我想实现一个链表数组来创建一个打印队列;有五个队列的数组。每个队列都代表一个用户正在打印发送到打印机的作业。
这是我目前拥有的代码:
#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;
}
此代码无法按预期工作,因为我无法将 "jobs" 添加到队列中。
我哪里做错了?
您的代码存在一些问题:
您正在用 C++ 编程,而不是 C,所以您应该简单地写 node *next
.
而不是 struct node *next
您的 insertNodes
函数 return 是指向列表头部的指针,因此您需要 return node*
,而不是 int
.
当您插入到具有现有头部的列表中时,您永远不会插入该项目。你必须做 Ptr->next = aNode
,而不是 Ptr->next = Ptr
。
在你的主函数中,你应该传递一个指向列表头部的指针给insertNodes
,但你实际上传递了一个int
。相反,请尝试 A[i] = insertNodes(A[i], num)
.
您将 float
存储在您的列表节点中,但输入 int
- 是否真的需要?
但是,由于您使用的是 C++,因此您可以完全依靠标准库已经提供的内容来避免其中的大部分陷阱。
只需 #include <deque>
,您就可以使用 std::deque
的所有内容(a ddouble-end queue) 提供,包括 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;
}
我想实现一个链表数组来创建一个打印队列;有五个队列的数组。每个队列都代表一个用户正在打印发送到打印机的作业。
这是我目前拥有的代码:
#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;
}
此代码无法按预期工作,因为我无法将 "jobs" 添加到队列中。 我哪里做错了?
您的代码存在一些问题:
您正在用 C++ 编程,而不是 C,所以您应该简单地写
node *next
. 而不是 您的
insertNodes
函数 return 是指向列表头部的指针,因此您需要 returnnode*
,而不是int
.当您插入到具有现有头部的列表中时,您永远不会插入该项目。你必须做
Ptr->next = aNode
,而不是Ptr->next = Ptr
。在你的主函数中,你应该传递一个指向列表头部的指针给
insertNodes
,但你实际上传递了一个int
。相反,请尝试A[i] = insertNodes(A[i], num)
.您将
float
存储在您的列表节点中,但输入int
- 是否真的需要?
struct node *next
但是,由于您使用的是 C++,因此您可以完全依靠标准库已经提供的内容来避免其中的大部分陷阱。
只需 #include <deque>
,您就可以使用 std::deque
的所有内容(a ddouble-end queue) 提供,包括 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;
}