Chained lists in C

Asked

Viewed 1,154 times

4

I have two lists in C, where you should include several records in the list of customers, and then make sure that some customer can book a car that is stored in the list of cars. The part of inclusion, removal and visualization of customers I can do well, the problem is time to get the customer to book a car, ie the cell with the customer’s name point to the list with the reserved car name.

 struct carro
{
        int codigo;
        char modelo[30];
        struct carro *proximo;
};

struct cliente
{
        int codigo;
        char nome[50];
        struct cliente *proximo;
        struct carro *reserva;
};


// Inserir no inicio da lista; 
struct cliente* insereInicio(struct cliente *pInicio,int codigo, char nome[50]){

        struct cliente *aux;
        aux = (struct cliente *)malloc(sizeof(struct cliente));
        aux->codigo = codigo;
        strcpy(aux->nome,nome);
        aux->proximo = pInicio;
        pInicio = aux;
        return pInicio;
}

void insereDepois(struct cliente *p, int codigo, char nome[50])
{
        struct cliente *aux;

        aux= (struct cliente *) malloc(sizeof(struct cliente));

        aux ->codigo=codigo;
        strcpy(aux->nome,nome);
        aux ->proximo=p->proximo;
        p->proximo=aux;

}  

struct cliente* insereOrdenado(struct cliente *pInicio, int codigo, char nome[50]){
        struct cliente *p, *q;
        if(pInicio == NULL || codigo < pInicio->codigo){
                return (insereInicio(pInicio, codigo, nome));          
        }
        p = pInicio;
        q = p;
        while(q != NULL && q->codigo > codigo){
                p = q;
                q = p->proximo;
        }
        if(q == NULL || q->codigo < codigo){
                insereDepois(p,codigo,nome);
        }
        else{
                printf("\nElemento ja existe");
        }
        return (pInicio);
}

main()
{
        struct ciiente *inicio;
        inicio = NULL;

        int opcao = 0;
        int codigo;
        char nome[50];

        while(1)
        {
            system("cls");
            printf("-----# Bem Vindo #-----\n");
            printf("\n1 - Incluir Cliente");
            printf("\n2 - Listar clientes");
            printf("\n3 - Sair do Programa\n");
            scanf("%d",&opcao);

            if(opcao == 1) {
                system("cls");
                printf("-----# Inserir novo Cliente #-----\n");
                printf("\nDigite o codigo do cliente: ");
                scanf("%d",&codigo);
                printf("Digite o nome do Cliente: ");
                fflush(stdin);
                scanf("%s",nome);

                inicio = insereOrdenado(inicio, codigo, nome);
            }   
            else if(opcao == 2)
            {
                system("cls");
                printf("-----# Clientes Cadastrados #-----\n");
                percorreLista(inicio);
            }
            else if(opcao == 3)
            {
                break;
            }
        }

My problem is that I don’t have the slightest idea how to make my customer list point to a particular node on my car list, so I was wondering if someone could guide me on how to do this exactly.

NOTE: I am new in C.

  • To make the reservation, will the user inform the customer code and the car code? A car can be reserved for two people at the same time (I suppose not)?

  • That first informs the customer’s code and then the car’s code so it can be booked. And the same car can’t be reserved for two people at the same time.

1 answer

1


First, you’ll have to change the struct carro to say who booked it:

struct cliente;

struct carro
{
    int codigo;
    char modelo[30];
    struct carro *proximo;
    struct cliente *reservado;
};

struct reserva
{
    struct reserva *proximo;
    struct carro *carro;
};

struct cliente
{
    int codigo;
    char nome[50];
    struct cliente *proximo;
    struct reserva *reserva;
};

Note that the first statement struct cliente is necessary because carro reference cliente and cliente reference carro. This is the way to make the compiler accept the cyclic dependency.

The structure reserva serves for me to have a list of cars for each person.

Let’s put two code search functions:

struct carro *localizarCarroPorCodigo(int codigo, struct carro *primeiro) {
    for (struct carro *c = primeiro; c != NULL; c = c->proximo) {
        if (c->codigo == codigo) return c;
    }
    return NULL;
}


struct carro *localizarClientePorCodigo(int codigo, struct cliente *primeiro) {
    for (struct cliente *c = primeiro; c != NULL; c = c->proximo) {
        if (c->codigo == codigo) return c;
    }
    return NULL;
}

Now we do the backup function:

void reservarCarro(int codigoCliente, int codigoCarro, struct cliente *primeiroCliente, struct carro *primeiroCarro) {
    struct cliente *cl = localizarClientePorCodigo(codigoCliente, primeiroCliente);
    if (cl == NULL) {
        printf("Nao existe o cliente com o codigo %d.", codigoCliente);
        return;
    }

    struct carro *ca = localizarCarroPorCodigo(codigoCarro, primeiroCarro);
    if (ca == NULL) {
        printf("Nao existe o carro com o codigo %d.", codigoCarro);
        return;
    }

    if (ca->reservado != NULL) {
        printf("Este carro ja esta reservado.");
        return;
    }

    struct reserva *nova = (struct reserva *) malloc(sizeof(struct reserva));
    nova->carro = ca;
    nova->proximo = cl->reserva;
    cl->reserva = nova;
    ca->reservado = cl;
    printf("Reserva efetuada com sucesso.");
}

And it’s also important to do the function of releasing a reserve. This one is similar to the previous one, but it’s easier. Starting from the car code, you find the customer. And then you remove the car from the reserve list and put the car customer to NULL. It goes something like this:

void liberarCarro(int codigoCarro, struct carro *primeiroCarro) {
    struct carro *ca = localizarCarroPorCodigo(codigoCarro, primeiroCarro);
    if (ca == NULL) {
        printf("Nao existe o carro com o codigo %d.", codigoCarro);
        return;
    }

    struct client *cl = ca->reservado;
    if (cl == NULL) {
        printf("Este carro nao estava reservado.");
        return;
    }

    struct reserva *r = NULL;
    struct reserva *s = cl->reserva;
    while (s != NULL) {
        if (s->carro == ca) {
            if (r != NULL) r->proximo = s->proximo;
            if (s == cl->reserva) cl->reserva = s->proximo;
            free(s);
            break;
        }
        r = s;
        s = s->proximo;
    }
    ca->reservado = NULL;
    printf("Reserva liberada com sucesso.");
}

And when entering the client, it’s important to make sure the code is unique. One way to do it is to enter the client, search for a client with that code and only let them enter if they do not find it (i.e., the search results NULL). Same goes for the car. Another strategy is to have the program generate the codes automatically instead of asking the users to type them and then the program informs the generated codes to the user.

To list all the cars of a customer:

void listarCarros(struct cliente *cliente) {
    for (struct reserva *s = cl->reserva; s != NULL; s = s->proximo) {
        printf("Codigo: %d - Modelo: %s", s->carro->codigo, s->carro->modelo);
    }
}
  • Thus there, the program would not allow more than one reservation for the same right customer?

  • @Danlima right. Looking at your struct cliente of your original code, I assumed this is intentional. If not, tell me I change the code accordingly.

  • In reality, the intention is that the customer can book more than one car at the same time, as long as the car is no longer reserved for another customer. Understands?

  • I was able to implement to insert more than one car for a customer, but I cannot list the cars that were reserved for a particular customer. I have no idea how to print what is on the customer->reservation. Any idea?

  • 1

    @Danlima Reply edited.

  • How would I do if I wanted to list all cars reserved for one customer? I already tried a " while(p->reserve != NULL)" printing the models of the cars inside the loop, but the program stops running.

  • @Danlima Reply edited again.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.