链表反转字符串中单词

    科技2022-07-16  134

    描述

    输入:here is tju 输出:tju is here

    代码(C++)

    #include <iostream> #include <vector> #include <string> using namespace std; struct SplitWords { vector<char> word; SplitWords *next; }; void Reverse(string s) { SplitWords *head = (SplitWords *) malloc(sizeof(SplitWords)); head->next = NULL; SplitWords *p; for (int i = 0; s[i] != '\0'; ++i) { if (s[i] == ' ') { p = (SplitWords *) malloc(sizeof(SplitWords)); p->next = head; head = p; continue; } head->word.push_back(s[i]); } p = head; while (p) { for (int i = 0; i < p->word.size(); ++i) { cout << p->word[i]; } cout << " "; p = p->next; } cout << endl; } int main() { string s = "here is tju"; Reverse(s); return 0; }
    Processed: 0.009, SQL: 8