问题:
将文本文件中的文本数据提取,并以此建立邻接表,再进行树的深度优先搜索。
遇到的问题:
在创建邻接表的时候,感觉逻辑有点混乱。
我先是把邻接表的头节点都先加载出来,再将子节点接到头节点上。
子节点接到头结点这个环节,感觉有点乱。
文本文件内容:
目标:
将该内容变成存储内的邻接表
并对该邻接表进行深度优先遍历
求指教!
以下为我的屎山代码XD(目前程序还是有问题的,问题在子节点连接到头节点那一块):
#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MAXSIZE 20
typedef struct Branch
{
int index;
struct Branch* next;
}branch;
typedef struct Tnode
{
char data[MAXSIZE];
branch* first;
}tnode;
void create(tnode tree[],char str[],int cnt) //创建邻接表
{
int j = 0, t = 0;
char string[MAXSIZE];
branch* p;
printf("一共有%d个头节点\n", cnt);
for (int i = 0; i < cnt; i++)
{
j = 0;
while (str[t] != '/') //遇到/就开始找换行符\n,并跳转到下一行,录入下一行头节点
{
tree[i].data[j] = str[t];
j++;
t++;
}
tree[i].data[j] = '\0'; //为tree[i].data加入终止符
tree[i].first = NULL;
while (str[t] != '\n'&&str[t]!=EOF) //跳转至下一行,准备录下一行的头节点
t++;
t++;
puts(tree[i].data); //将该行的头节点中的串打印出来以检验头节点的串是否成功录入
}
//头节点初始化完成,接下来将子节点连接到
t = 0;
for (int i = 0; i < cnt; i++)
{
while (str[t] != '/') //先跳过头节点
t++;
t++;
p = (branch*)malloc(sizeof(branch));
while (t != '\n')
{
j = 0;
for (int n = 0; n < strlen(string); n++)//字符串清空
string[n] = '\0';
while (str[t] != '/')//将字符串截取出来
{
string[j] = str[t];
j++;
t++;
}
//此时str[t]=='/'
string[j] = '\0';
printf("子串为:");
puts(string);
for (int n = 0; n < cnt; n++)
{
if (!strcmp(tree[n].data, string))
p->index = n;
}
p->next = tree[i].first;//将p接入头节点中
tree[i].first = p;
t++; //使t指向下一个单词开头
p = (branch*)malloc(sizeof(branch));
}
//此时t指向\n
t++; //将t指向下一行第一个字符
}
}
void DFS(tnode tree[]) //对邻接表进行深度优先遍历
{
}
void visit(tnode* node,char str[]) //对结点进行访问
{
if (!strcmp(node->data, str))
{
printf("该结点存在!");
}
}
void FillInText(char str[], FILE* fp) //将文件中内容传入str中
{
char ch;
int length = 0;
ch = fgetc(fp);
while (ch != EOF)
{
str[length] = ch;
ch = fgetc(fp);
length++;
}
str[length] = '\0';
}
int getCount(char str[]) //获取邻接表头节点个数
{
int cnt = 0;
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == '\n')
cnt++;
}
return cnt + 1;
}
int main()
{
FILE* fp;
tnode tree[MAXSIZE];
char ch, str[100];
fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("文件打开失败\n");
exit(0);
}
FillInText(str, fp);
printf("文件中的文本内容为:\n");
puts(str);
create(tree, str,getCount(str));
fclose(fp);
return 0;
}