Linked list with multiple parent and child nodes

后端 未结 6 2101
时光说笑
时光说笑 2021-01-06 00:52

I am trying to design a program that takes in data from a file, after which it gives numbering to unique data, linked list also contains parent and child lists.

Data

6条回答
  •  广开言路
    2021-01-06 01:41

    Linked and doubly-linked lists are a specific variety of directed graphs which can be optimized into the head/tail, data/next/prev structure you're familiar with. Since you're broadening its capabilities, you lose that specificity, and want to go back to the generic directed graph structure and work from there.

    A directed graph is most easily described with an adjacency list: image of graphs with adjacency lists

    You can implement that with as a list of lists, or an array of lists, or a jagged array, or however you like. Now, on the right, I've drawn a doubly-linked list in directed graph form. Since the next pointers are different from prev pointers, your adjacency list needs to keep those separate. So it will actually be a list of dual lists:

    typedef struct _BPNode { // "Back-Pointing Node"
        void *data;
        struct _BPNode *nexts[];
        struct _BPNode *prevs[];
    } Node;
    
    typedef struct _BPGraph { // "Back-Pointing Graph"
        Node **allNodes;
    } BPGraph;
    

    Or something like that. Disclaimer: I didn't test this in a compiler. And just in case, here's a guide on how to read some of the declarations in there.

    Alternatively, you can create two directed graphs, one running forward, and one running backward. However, that would take more memory than this "back-pointing" graph. It would also run slower (more cpu cache misses), would be less intuitive, and would be more troublesome to free memory for.

提交回复
热议问题