Linked list with multiple parent and child nodes

后端 未结 6 2127
时光说笑
时光说笑 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-06 01:37

    You can have structure like this:

    struct abcd{
     char data;
     struct abcd *next[10];  //array of next nodes
     struct abcd *prev[10];  //array of previous nodes
    }
    

    When accessing next nodes you can do node->next[i] instead of node->next, where 0<= i < 10. When allocating/creating node reset all array elements to NULL so that you don't have garbage for uninitialized nodes.

    So lets suppose you added node for 'A', then you can add nodes for 'B' and 'C' as

    int idx;
    //find index for free element.
    for(idx = 0; nodeA->next[idx] && idx < 10; idx++)
       ;
    if(idx == 10)
       //dont have free space
    nodeA->next[idx] = nodeB;
    nodeB->prev[0] = nodeA;
    
    //similarly add for C, you may have to check for appropriate idx!
    nodeA->next[idx++]] = nodeC;
    nodeC->prev[0] = nodeA;
    

    With this basically you can create node which can have at most 10 next or previous nodes.

    Array is for simplicity, you can also do struct abcd **next; where you can have dynamic number of next/prev nodes. You will have to allocate the memory appropriately though.

提交回复
热议问题