我想写一个十字链表(有向图),但是遇到了无法给结构体指针赋值的问题。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAXVEX 100
struct edgeNode //边表结点
{
int tailVex, headVex;
edgeNode *tailLink, *headLink;
};
struct vertexNode //顶点表结点
{
int data;
edgeNode *firstIn, *firstOut;
};
struct graph_OL //十字链表结构
{
vertexNode OLList[MAXVEX];
int numVertexes;
};
void createOLGraph(graph_OL* g) //生成一个十字链表
{
printf("请输入结点数:");
scanf("%d", &g->numVertexes);
setbuf(stdin, NULL);
for (int i = 0; i < g->numVertexes; i++)
{
printf("请输入结点的值:");
scanf("%d", &g->OLList[i].data);
setbuf(stdin, NULL);
}
printf("构造十字链表的出度链:\n");
for (int i = 0; i < g->numVertexes; i++) //连接每一个结点的弧尾
{
int tTail;
edgeNode* p = g->OLList[i].firstOut;
edgeNode *tEdgeNode;
int flag = 1;
printf("第%d个结点的出度链:\n", i);
if (p)
{
while (1)
{
printf("请输入一个弧尾,-1表示输完了所有的弧尾:");
scanf("%d", &tTail);
setbuf(stdin, NULL);
if (tTail == -1)
{
if (flag)
{
g->OLList[i].firstOut = NULL;
}
else {
p->tailLink = NULL;
}
break;
}
else {
tEdgeNode = (edgeNode*)malloc(sizeof(edgeNode));
if (tEdgeNode)
{
tEdgeNode->headVex = i;
tEdgeNode->tailVex = tTail;
if (flag)
{
g->OLList[i].firstOut = tEdgeNode;
p = tEdgeNode;
flag = 0;
}
else {
p->tailLink = tEdgeNode;
p = tEdgeNode;
};
}
}
}
}
}
printf("构造十字链表的入度链:\n");
for (int i = 0; i < g->numVertexes; i++) //连接每一个链表的弧头
{
int tIn;
edgeNode* tHead = g->OLList[i].firstIn;
edgeNode* fHead = NULL;
int flag = 1;
printf("第%d个结点的入度链:\n", i);
while (1)
{
printf("请输入一个弧头,-1表示输完了所有的弧头:");
scanf("%d", &tIn);
setbuf(stdin, NULL);
if (tIn == -1)
{
if (flag)
{
g->OLList[i].firstIn = NULL;
}
else {
tHead->tailLink = NULL;
}
break;
}
else {
fHead = g->OLList[tIn].firstOut;
if (fHead)
{
while (fHead->headVex != i) //此处提示fHead是nullptr
{
fHead = fHead->tailLink;
}
if (flag)
{
g->OLList[i].firstIn = fHead;
tHead = fHead;
flag = 0;
}
else {
tHead->headLink = fHead;
tHead = fHead;
}
}
}
}
}
}
void showOLGraph(graph_OL g) //显示十字链表
{
edgeNode* t;
printf("显示十字链表的出度链:\n");
for (int i = 0; i < g.numVertexes; i++)
{
printf("数组下标:%d,data值:%d,", i, g.OLList[i].data);
if (t = g.OLList[i].firstOut)
{
printf("无弧尾\n");
}
else {
while (t)
{
printf(" ——> 下标:%d", t->headVex);
t = t->tailLink;
}
printf("\n");
}
}
printf("\n");
printf("显示十字链表的入度链:\n");
for (int i = 0; i < g.numVertexes; i++)
{
printf("数组下标:%d,data值:%d,", i, g.OLList[i].data);
if (t = g.OLList[i].firstIn)
{
printf("无弧头\n");
}
else {
while (t)
{
printf(" ——> 下标:%d", t->tailVex);
t = t->headLink;
}
printf("\n");
}
}
}
int main()
{
graph_OL myOLGraph;
createOLGraph(&myOLGraph);
showOLGraph(myOLGraph);
}