How does a chained list work in C?

Asked

Viewed 508 times

0

I’m doing a job for college and I still don’t fully understand the logic behind a chained list in C.

I need to log in, name and value in a record, of which I created a struct (set of variables); I created another struct to be my nodes and a third struct to be the chained Ita.

How do these three structs relate to each other and why do they all have pointers to the next? It would not only be necessary for nodes to have pointers to the next?

There is a difference from the traditional examples. In this example, why does the log struct have pointer? It would not be enough to pointer the node struct?

typedef struct registro_st{         // sequência de objetos do mesmo tipo
        char login[50];
        char nome[50];
        float valor;
        struct registro *prox;
    } registro;


typedef struct nodo_st{
    registro dado;
    struct nodo *prox;
} nodo;


typedef struct Lista_st{
    nodo *cabeca;
    nodo *cauda;
    int tamanho;
} lista;

1 answer

1

I’m no expert, but for me there are unnecessary things there, I think you could simplify for this guy:

typedef struct registro_st{
    char login[50];
    char nome[50];
    float valor;
    struct registro *prox;
} registro;

typedef struct Lista_st{
    registro *cabeca;
    registro *cauda;
    int tamanho;
} lista;

On the chained list, basically each "object" in the list will point to the next element of the list, if any. - This is simply chained up. If it is double chained, each "object" instead of just pointing to the next, will also point to the previous one.

And in the case of your code, you will have the pointers at the beginning and end of the list. (head and tail)

inserir a descrição da imagem aqui

I hope I’ve been of some help!

  • Perfect! That I understand. What I don’t understand is why the first struct has a self-referenced pointer. The list I understand, because that way we can point out the location of the next Node.

  • The pointer referencing itself is already self explained in the photo @Tiago posted. The structure of all the data will be the same, and what will change would only be the "object" in the case the value. So he points to the Next element equal to him, thus making the list chained.

Browser other questions tagged

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