首页 > 解决方案 > A flexible list with indefinite number of nodes

问题描述

I am supposed to make a linked list that takes in strings and prints them out in the reverse order. Normally I'd ask the number of nodes that need to be created, and then ask for the data in a for loop until we're done.

typedef struct word_st {
   string word; // string is meant to be a pointer to a struct
   word_st *next;
 }

But the problem is, the number of nodes isn't known until runtime. So I have to keep asking for data until the user is done. I'm not really sure where to start/how to do that and can't seem to find anything on the internet either. So a hint would be very helpful.

I have my insert function and the print function looks fairly simple too.

    word_t *insert_2(word_t* head, string text) {
    word_t * p = NULL;
    word_t * temp = (word_t*) malloc(sizeof(word_t));

    temp -> word = text;
    temp -> next = NULL;
    if(head == NULL) {
      head = temp;
    } else {
      p = head;
    } while(p -> next != NULL) {
      p = p -> next;
    }
    p -> next = temp;
   return head;
   }  

标签: clinked-list

解决方案


相反,将next替换为prev

typedef struct word_st {
    string word; // string is meant to be a pointer to a struct
    word_st * prev;
}

和功能:

word_t *insert_2(word_t* head, string text) {
    word_t * nextHead = (word_t*) malloc(sizeof(word_t));
    nextHead -> word = text;
    nextHead -> prev = NULL;

    // Check first element of LIFO 
    if( head == NULL ) {
        return nextHead;
    }

    nextHead -> prev = head;
    return nextHead;
}

我希望它编译并工作。

笔记:

for(word_t * head = last ; head->prev != NULL ; head = head->prev )
{
    // Do the job
    ;
}

推荐阅读