简体   繁体   中英

Split words with linked list in C++

I have problem with linked list. I wrote a function want to split a sentence into words. Like I have a sentence "I love you", and it splits into 3 words "I", "love", "you". I have the head pointer to the first letter of the sentence. And the function will return an array with every words' head pointers.

It works fine only has one problem. If one word just have one letter. It will combine with the second word. Like "I love you", it will give the words as "I love" and "love", "you".

I have thought for a long time and other functions work well. I think the problem is in the for loop, can anyone helps?

Node* SplitToWords(Node* cursor){
int i=CountWords(cursor);

Node* array=new Node[i];
Node* t;
t=cursor;

for (int j=0; j<i-1; j++) {
    array[j]=*t;
    t=t->link;
    while (t->data!=' ') {
        cursor=t;
        t=t->link;
    }
    t=t->link;
    cursor->link=NULL;
}
array[i-1]=*t;

return array;
}

You process first letter of a word wrong. This array[j]=*t; copy node to array. And in the end cursor->link=NULL; doesn't make any changes in this copy if you word one letter long.
To fix you can remember first node and insert it into array in the end of the for loop

for (int j=0; j<i-1; j++) {
    Node *first_letter = t;
    t=t->link;
    while (t->data!=' ') {
        cursor=t;
        t=t->link;
    }
    t=t->link;
    cursor->link=NULL;
    array[j]=*first_letter;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM