如何创建可作为队列使用的节点链表 现有Node结构体如何实现队列
基于现有Node结构体实现链表队列的方案
实现原理
队列遵循*先进先出(FIFO)*的操作规则,基于你已定义的单链表Node结构体,只需额外维护头尾两个指针即可完成队列实现:
- 头指针
front:指向队列的第一个节点,用于出队、遍历队列 - 尾指针
rear:指向队列的最后一个节点,用于快速入队,无需每次遍历全链表
核心操作实现
- 入队:创建新节点,若队列为空则头尾指针都指向新节点;否则将尾节点的next指针指向新节点,再更新尾指针为新节点
- 出队:取出头节点存储的数值,更新头指针为头节点的next指针,释放旧头节点的内存避免泄漏;若出队后队列为空,将尾指针也置为空
- 遍历:从头指针开始循环遍历所有节点直到next为空
适配你需求的完整修改代码
#include <iostream> #include <fstream> #include <string> #include <unistd.h> using namespace std; struct Node { int value; Node* next; // 构造函数 Node(int a, Node* next1 = nullptr) { value = a; next = next1; } }; // 队列头尾指针,也可封装到队列类中,此处适配你的现有代码结构 Node* front = nullptr; Node* rear = nullptr; // 入队函数 void enqueue(int val) { Node* newNode = new Node(val); if (rear == nullptr) { // 队列为空时头尾都指向新节点 front = rear = newNode; return; } rear->next = newNode; rear = newNode; } // 出队函数,返回-1表示队列为空 int dequeue() { if (front == nullptr) { return -1; } Node* temp = front; int val = temp->value; front = front->next; // 出队后队列为空时重置尾指针 if (front == nullptr) { rear = nullptr; } delete temp; return val; } void drawTriangle(int lines); void displayList(Node* head); int main() { string lsCmd = "ls ../../Assignment8/Assignment8/triangle*.txt > Assignment9jobQueue.txt"; ifstream triangleFile; string files; system(lsCmd.c_str()); triangleFile.open("Assignment9jobQueue.txt"); // 第一步:将所有任务读入链表队列 while (getline(triangleFile, files)) { ifstream temp; string strTemp; temp.open(files); getline(temp, strTemp); int lines = stoi(strTemp); enqueue(lines); // 入队操作 temp.close(); remove(files.c_str()); } triangleFile.close(); // 第二步:遍历队列处理任务 if (front == nullptr) { cout << "No files to process . . ." << endl; sleep(10); return 0; } displayList(front); cout << endl; while (front != nullptr) { int lines = dequeue(); // 出队操作 cout << "Drawing Triangle: " << endl; drawTriangle(lines); } return 0; } // 以下为示例实现,可替换为你原有实现 void drawTriangle(int lines) { for (int i = 1; i <= lines; i++) { for (int j = 0; j < lines - i; j++) { cout << " "; } for (int k = 0; k < 2*i -1; k++) { cout << "*"; } cout << endl; } } void displayList(Node* head) { cout << "当前队列任务(lines值):"; Node* temp = head; while (temp != nullptr) { cout << temp->value << " "; temp = temp->next; } }
注意事项
- 上述实现完全保留了你定义的Node结构体作为链表节点,符合项目要求的链表队列实现规则
- 代码调整了原有逻辑,先将所有任务全部入队存储到链表,再逐个出队处理,符合队列的使用逻辑
- 增加了内存释放逻辑,避免出现内存泄漏问题
内容的提问来源于stack exchange,提问作者Giovanny
相关产品推荐
相关产品推荐

