Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

c - 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;
   }  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In reverse, replace next by prev:

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

And the function:

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;
}

I hope It compiles and work.

Note:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...