【问题标题】:How to create a linked list of nodes to be used as a queue如何创建用作队列的节点链表
【发布时间】:2021-05-25 18:24:17
【问题描述】:

请就如何创建节点的链接列表用作队列提供任何建议?我完成了节点,但不确定如何将它实现到队列linked-list。我运行程序,它可以按顺序获取文件,但程序必须具有实现队列所需的链表结构。

struct Node {
    int value;
    Node* next;
    // Constructor
    Node(int a, Node* next1 = nullptr) // Constructor function inside (inline in) the struct definition
    {
        value = a;
        next = next1;
    }
};
void drawTriangle(int lines);
void displayList(Node*);
int main()
{
    // Format a DOS system command string
    string lsCmd = "ls ../../Assignment8/Assignment8/triangle*.txt > Assignment9jobQueue.txt"; //Open Assignment9jobQueue.txt to get names of triangle job files (will need to parse file names from this file)
    // Define an input file object
    ifstream triangleFile;
    // Loop looking for triangle job files
    // System call to find files
    int lines = 20;
    Node* texts = nullptr;
    string files;
    system(lsCmd.c_str());
    triangleFile.open("Assignment9jobQueue.txt");
    //getline works well for parsing out file names (store them in a queue)
    while (getline(triangleFile, files)) { // Process files in a while loop (while there are names in the file)
        ifstream temp;
        string strTemp;
        temp.open(files);
        getline(temp, strTemp);
        lines = stoi(strTemp);
        texts = new Node(lines);
        displayList(texts);
        cout << endl;
        cout << "Drawing Triangle: " << endl;
        drawTriangle(lines); // Draw the triangle
        remove(files.c_str());
    }
    if (!getline(triangleFile, files)) {
        cout << "No files to process . . ." << endl;
        sleep(10);
    }

    return 0;
}

【问题讨论】:

  • 您可能希望从拥有head 指针开始。
  • 您至少应该尝试构建链接列表。

标签: c++ linked-list queue


【解决方案1】:

链表只是指向节点的节点。您需要一个 head 指针,该指针指向您用来遍历链表的第一个节点。队列是先进先出的,因此您应该实现一个 pop() 函数,该函数删除并返回列表的最后一个节点,以及一个指向 headpush(node) 函数,然后更新 head 指针指向你刚刚添加的节点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多