我首先想创建一个带有用户输入的字符串的链表(直到用户输入句号为止),然后递归地将其反转,最后打印新的链表。 下面的程序是我目前为止得到的:它正在编译,但只显示最后一个单词。我认为在某个时候我给之前的某个字符串的内存位置分配了一个新的字符串。 我相对于C++比较新,无法想象我何时出错了。 任何评论或提示都将不胜感激! 谢谢
#include <iostream>
#include <string>
using namespace std;
//create a node that reads a string and points to next one
struct Node
{
string word;
Node * next;
};
//create current and temporary pointers for Node
Node * current;
Node * temp;
//function to reverse Node
void Reverse(struct Node * p, Node * hdr)
{
if (p->next == NULL)
{
hdr = p;
return;
}
Reverse(p->next, hdr);
struct Node * q = p->next;
q->next = p;
p->next = NULL;
return;
}
//function to print linked list
void print(Node * header)
{
cout << "The reversed linked list is: " << endl;
Node * ptr = header;
while(ptr!=NULL)
{
cout << ptr->word << " ";
ptr = ptr->next;
}
}
int main()
{
//Ask user to input keyboard strings
cout << "Please insert strings seperated by white spaces (isolated full-stop to finish): " << endl;
string input;
//create head pointer
Node * head = new Node;
head->next = NULL;
//create loop to read words and insert them into linked list
while(true)
{
cin >> input;
if (input == ".")
break;
current = new Node;
current->word = input;
current->next = head->next;
head->next = current;
}
//get and output reversed linked list
Reverse(current, head);
print(head);
cout << " ." << endl;
return 0;
}