How to implemet linked lists using arrays in C?

Discussion in 'Programming' started by virtualmisc, Sep 28, 2009.

  1. #1
    How can we implement linked lists using arrays in C?
    This is one of my project assignments?
    Someone please help me with this or give some reference.
     
    virtualmisc, Sep 28, 2009 IP
  2. caprichoso

    caprichoso Well-Known Member

    Messages:
    433
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    110
    #2
    Implementing linked list using arrays sounds a little weird. You should implement a linked list for getting rid of the arrays. :)

    Anyway, I guess you can declare a struct like

    
    struct demo {
      int value; // One or more fields for your data
      int next; // Array index of the next list item
    } t_item;
    
    ...
    t_item list[100];
    ...
    
    list[0].value = ...;
    list[0].next = 4;
    
    list[4].value = ...;
    list[4].next = 1;
    
    list[1].value = ...;
    list[1].next = 2;
    
    list[2].value = ...;
    list[2].next = 3;
    
    list[3].value = ...;
    list[3].next = -1;
    ...
    t_list * nextitem = &list[0]; // Assume the first element has no data and is always at index zero
    do {
      nextitem = &list[nextitem->next];
      printf("%d\n", nextiem->value);
    }
    while(nextitem->next != -1);
    
    Code (markup):
     
    caprichoso, Sep 28, 2009 IP
  3. ankit_frenz

    ankit_frenz Active Member

    Messages:
    1,111
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    63
    #3
    thats a perfect response..if you want to build doubly linked list..use three fileds like:-

    simillarly you can also implement multi filed list..infcat using this strcutrue you can even implement weighted graphs and Automatas
     
    ankit_frenz, Sep 28, 2009 IP
  4. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #4
    kmap, Sep 28, 2009 IP