【发布时间】:2026-02-20 08:00:01
【问题描述】:
我想用字母构建一个图表,但是出了点问题。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct AdjListNode
{
char *dest;
struct AdjListNode* next;
};
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
struct Graph
{
int V;
struct AdjList* array;
};
struct AdjListNode* newAdjListNode(char *dest){
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;}
struct Graph* createGraph(int V){
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;}
void addEdge(struct Graph* graph, char *src, char *dest){
// Add an edge from src to dest. A new node is added to the adjacency
// list of src. The node is added at the beginin
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[0].head;
graph->array[0].head = newNode;
// Since graph is undirected, add an edge from dest to src also
newNode = newAdjListNode(src);
newNode->next = graph->array[1].head;
graph->array[1].head = newNode;}
void printGraph(struct Graph* graph){
int v;
for (v = 0; v < graph->V; ++v)
{
struct AdjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl)
{
printf("-> %s", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");}}
int main(){
// create the graph given in above fugure
int V = 5;
struct Graph* graph = createGraph(V);
addEdge(graph, "a", "b");
addEdge(graph, "a", "e");
addEdge(graph, "b", "c");
addEdge(graph, "b", "d" );
addEdge(graph, "b", "e");
addEdge(graph, "c", "d");
addEdge(graph, "d", "e");
// print the adjacency list representation of the above graph
printGraph(graph);
return 0;}
我的输出是这样的:
e->d->e->d->a->b->c->b->a->
我的输出应该是:
a->b->e
b->a->c->d->e
c->b->d
d->b->c->e
e->a->b->d
请帮帮我。我再次问了一个不同的问题。我想要这个输出。我想用字母创建 adjList
【问题讨论】:
标签: c data-structures graph