Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...