У меня вкратце проблема с циклом for с 2 переменными.
Одна переменная классически i=0 > to the end of bound
и
, вторая *(ptr->cost)
похожа на это и показывает значение с помощью указателя.
У меня проблема со второй, на самом деле я не могу ее поместить дляпетля.Я получаю переменную cost от пользователя и хочу напечатать их i и переменные стоимости вместе.Но мои коды просто печатают переменные i и одну переменную стоимости.
Это моя связанная часть кода:
void print_graph(struct node *ad[],int no_of_nodes){
struct node *ptr = NULL;
int i,j;
for(i=0; i<no_of_nodes; i++){
ptr = ad[i];
printf("\n Number %d node cost is = %d and its neighbours are : ",i+1,*(ptr->cost));
while(ptr != NULL){
printf("%d\t ",ptr->data,*(ptr->cost));
ptr = ptr->next;
}
}
}
и результат
Узел 1 должен быть 50, но выходные данные показывают его 70.
Также я думаю, что переменная Cost не включена в цикл for, поэтому она поворачивается только один раз, а также в обратном порядке.Как можно решить эту проблему?
Это весь мой код
struct node{
int data;
struct node *next;
int* cost;};
typedef struct node nodes;
void read_graph(struct node *ad[], int no_of_nodes);
void print_graph(struct node *ad[],int no_of_nodes);
void main()
{
int i,j,k,nodes;
printf("\nEnter the number of nodes :");
scanf("%d",&nodes);
struct node *adj[nodes];
for(i=0; i<nodes; i++)
adj[i] = NULL;
read_graph(adj,nodes);
print_graph(adj,nodes);
}
void read_graph(struct node *ad[], int no_of_nodes){
struct node *new_node;
int i,j,k,val;
int costs[10];
for(i=0; i< no_of_nodes; i++){
struct node *last = NULL;
printf("\nFor Node : %d\n",i+1);
printf("\n%5d. nodes cost is: ",i+1);
scanf("%d",&costs);
printf(" Number of neighbours = ",i+1);
scanf("%d",&k);
for(j=0; j<k; j++){
printf(" Enter the %d. neighbours of %d : ",j+1,i+1);
scanf("%d",&val);
new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = val;
new_node->next = NULL;
(*new_node).cost = costs; //////////////////////////////////////
if(ad[i]== NULL)
ad[i] = new_node;
else
last->next = new_node;
last = new_node;
}
}
}
void print_graph(struct node *ad[],int no_of_nodes){
struct node *ptr = NULL;
int i,j;
for(i=0; i<no_of_nodes; i++){
ptr = ad[i];
printf("\n Number %d node cost is = %d and its neighbours are : ",i+1,*(ptr->cost));
while(ptr != NULL){
printf("%d\t ",ptr->data,*(ptr->cost));
ptr = ptr->next;
}
}
}
Наконец, кто-нибудь может подсказать мне, как мне следовать по пути к сумме затрат и сравнить их, чтобы найти, какой из них самый низкий