链接列表数组(5个队列)

时间:2018-05-19 11:07:44

标签: c++ arrays linked-list queue singly-linked-list

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

这是我目前的代码:

#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;
}

此代码无法正常工作,因为我无法添加&#34; jobs&#34;到队列。 我哪里出错?

1 个答案:

答案 0 :(得分:1)

您的代码存在许多问题:

  1. 您使用C ++编程,而不是C编程,因此您应该只编写struct node *next而不是node *next

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

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

  4. 在您的main函数中,您需要将指向列表头部的指针传递给insertNodes,但实际上是将int传递给它。相反,请尝试A[i] = insertNodes(A[i], num)

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

  6. 但是,由于您使用的是C ++,因此您可以完全依靠标准库已经提供的内容来避免大部分陷阱。

    只需#include <deque>即可使用std::deque所有内容( d ouble- e nded que ue )提供,包括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;
    }
    
相关问题