我创建了一个程序,在这些节点之间添加节点和边缘。现在我想找到哪个节点有最大连接边数。这是我的代码:
const int N = 15;
struct graf {
int key;
graf *next;
};
void init(graf *gr[]) {
for (int i = 0; i<N; i++) {
gr[i] = NULL;
}
}
int search_node(graf *gr[], int c) {
int flag = 0;
for (int i = 0; i<N; i++) {
if (gr[i]) {
if (gr[i]->key == c)flag = 1;
}
}
return flag;
}
int search_arc(graf *gr[], int c1, int c2) {
int flag = 0;
if (search_node(gr, c1) && search_node(gr, c2)) {
int i = 0;
while (gr[i]->key != c1)
i++;
graf *p = gr[i];
while (p->key != c2 && p->next != NULL)
p = p->next;
if (p->key == c2)
flag = 1;
}
return flag;
}
void add_node(graf *gr[], int c) {
if (search_node(gr, c))
printf("Edge existing !\n");
else {
int j = 0;
while (gr[j] && (j<N))j++;
if (gr[j] == NULL) {
gr[j] = new graf;
gr[j]->key = c;
gr[j]->next = NULL;
}
else
printf("Overflow !\n");
}
}
void add_arc(graf *gr[], int c1, int c2) {
int i = 0;
graf *p;
if (search_arc(gr, c1, c2))
printf("there is edge from node %s to node %s", c1, c2);
else {
if (!(search_node(gr, c1)))
add_node(gr, c1);
if (!(search_node(gr, c2)))
add_node(gr, c2);
while (gr[i]->key != c1)
i++;
p = new graf;
p->key = c2;
p->next = gr[i]->next;
gr[i]->next = p;
}
}
int get_graph_rank(graf*& gr,int i=0)
{
int max = NULL;
if (gr != NULL)
{
//i think to use recursion but i don't know how to start ...
}
return max;
}
int main() {
int c, k;
int menu = NULL, br = NULL;
graf *gr1[N];
init(gr1);
do
{
printf("1. add node\n");
printf("2. add edge\n");
printf("3.get the rang\n");
printf("0. exit\n");
do {
scanf_s("%d",&menu);
} while (menu<0 || menu>4);
switch (menu) {
case 1:
printf("enter edge: ");
scanf_s("%d", &c);
add_node(gr1, c);
break;
case 2:
printf("begining edge: ");
scanf_s("%d", &c);
printf("ending edge: ");
scanf_s("%d", &k);
add_arc(gr1, c, k);
break;
case 3:
get_graph_rank(*gr1);
break;
}
} while (menu != 0);
delete gr1;
}
我希望你能帮助我编写函数的逻辑,该函数将返回节点的值,该节点的最大边连接到它,并且如果有多个连接边数相同的节点,则返回NULL.Thanks in advice .....
答案 0 :(得分:0)
看起来代码使用单链接列表节点来表示图节点。这意味着您的节点不能超过1(传出)边缘。不确定这样的图表表示是否有用。
另一种方法是表示图形是使用数组作为图形节点值并将边缘表示为adjacency matrix N-by-N,其中每个元素都指定是否存在从节点A到节点B的边缘。