Цикл с двумя переменными (одна указатель) в программировании на C - PullRequest
0 голосов
/ 06 июня 2018

У меня вкратце проблема с циклом 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;
        }
    }  
}

и результат
enter image description here

Узел 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;
        }
    }
}

Наконец, кто-нибудь может подсказать мне, как мне следовать по пути к сумме затрат и сравнить их, чтобы найти, какой из них самый низкий

1 Ответ

0 голосов
/ 06 июня 2018
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node{
    int data;
    int cost;
    struct node *next;
} node;

void read_graph(node *ad[], int no_of_nodes);
void print_graph(node *ad[],int no_of_nodes);

void main()
{
    int i,j,k,nodes;
    printf("\nEnter the number of nodes :");
    scanf("%d",&nodes);

    node *adj[nodes];
    memset(adj, 0, sizeof(node *) * nodes);
    read_graph(adj,nodes);
    print_graph(adj,nodes);     
}

void read_graph(node *ad[], int no_of_nodes){
    node *new_node;
    node *last;
    int i,j,k,val;  
    int cost;
    for(i=0; i< no_of_nodes; i++){
        last = NULL;

        printf("\nFor Node : %d\n",i+1);        
        printf("\n%5d. nodes cost is: ",i+1);
        scanf("%d",&cost);

        printf("    Number of neighbours = ");
        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 = (node*) malloc(sizeof(node));
            new_node->data = val;
            new_node->next = NULL;
            new_node->cost = cost;

            if(ad[i]== NULL)
                ad[i] = new_node;
            else
                last->next = new_node;
            last =  new_node;           
        }
    }
}

void print_graph(node *ad[],int no_of_nodes){
    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 = ptr->next;
        }
    }
}

Код хорошо работает для вашего запроса, однако я предлагаю переопределить структуру узла, например:

typedef struct node
{
    int id;
    int cost;
    int neighbours;
} node;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...