如何在逐行文本转链表节点场景下仅为每行首节点实现down指针?
实现每行首节点的down指针连接
首先定义节点结构体,需要包含字符数据、横向连接的next指针,以及行之间连接的down指针:
typedef struct Node { char data; struct Node* next; struct Node* down; } Node;
核心思路是记录上一行的首节点,当处理完当前行的字符链表后,把上一行首节点的down指针指向当前行的首节点。具体步骤如下:
- 初始化
head(整个结构的头节点,指向第一行首节点)和prev_row_head(记录上一行的首节点)为NULL。 - 逐行读取文本文件的内容:
- 对每行字符串,先创建该行的首节点,再依次创建后续字符节点,用
next指针串联成横向链表。 - 如果是第一行,直接将
head指向该行首节点;否则,将prev_row_head->down指向当前行首节点,完成行之间的连接。 - 更新
prev_row_head为当前行的首节点,继续处理下一行。
- 对每行字符串,先创建该行的首节点,再依次创建后续字符节点,用
完整示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node { char data; struct Node* next; struct Node* down; } Node; // 创建单个节点的工具函数 Node* create_node(char c) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = c; new_node->next = NULL; new_node->down = NULL; return new_node; } int main() { FILE* file = fopen("input.txt", "r"); if (!file) { perror("Failed to open file"); return 1; } Node* head = NULL; Node* prev_row_head = NULL; char buffer[256]; // 根据实际需求调整缓冲区大小 while (fgets(buffer, sizeof(buffer), file) != NULL) { // 移除换行符 buffer[strcspn(buffer, "\n")] = '\0'; int line_len = strlen(buffer); if (line_len == 0) continue; // 跳过空行 // 构建当前行的字符链表 Node* current_row_head = create_node(buffer[0]); Node* current_char = current_row_head; for (int i = 1; i < line_len; i++) { current_char->next = create_node(buffer[i]); current_char = current_char->next; } // 连接行之间的down指针 if (!head) { head = current_row_head; // 第一行初始化head } else { prev_row_head->down = current_row_head; // 上一行首节点指向当前行首节点 } prev_row_head = current_row_head; } fclose(file); // 测试遍历输出 Node* row_ptr = head; while (row_ptr) { Node* char_ptr = row_ptr; while (char_ptr) { printf("%c ", char_ptr->data); char_ptr = char_ptr->next; } printf("\n"); row_ptr = row_ptr->down; } // 注意:实际项目中需要遍历所有节点释放内存,避免内存泄漏 return 0; }
关键细节说明:
prev_row_head是核心变量,它持续记录上一行的首节点,确保当前行能通过down指针和上一行建立连接。- 只处理每行首节点的
down指针,符合你“无需为所有节点添加down指针”的要求。 - 代码中加入了跳过空行的逻辑,避免空行产生无效节点。
内容的提问来源于stack exchange,提问作者Kate Black
相关产品推荐
相关产品推荐

