c++ - 递归地反转字符串链表

标签 c++ recursion linked-list

我想首先创建一个包含用户字符串的链表(直到用户输入句号),然后递归地反转它,然后打印新列表。 下面的程序是我到目前为止得到的:它正在编译但只显示最后一个词。我估计在某个时候我正在将一个新字符串分配给以前的字符串之一的内存位置。 我是 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;
}

最佳答案

试试这个:

void recursiveReverse(struct node** head_ref)
{
    struct node* first;
    struct node* rest;

    /* empty list */
    if (*head_ref == NULL)
       return;   

    /* suppose first = {1, 2, 3}, rest = {2, 3} */
    first = *head_ref;  
    rest  = first->next;

    /* List has only one node */
    if (rest == NULL)
       return;   

    /* reverse the rest list and put the first element at the end */
    recursiveReverse(&rest);
    first->next->next  = first;  

    /* tricky step -- see the diagram */
    first->next  = NULL;          

    /* fix the head pointer */
    *head_ref = rest;              
}

引用http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/

关于c++ - 递归地反转字符串链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33972271/

相关文章:

c++ - uint8_t 不能用 cout 打印

c++ - 通过指针成员传递类

java - 频率包 - getFrequencyOf(aData)

c - C 中链接列表示例中奇怪的核心转储错误

c++ - 表达式的行为 : Defined or Undefined?

c++ - 将模板与作用域在函数内的匿名类一起使用

haskell - 埃拉托斯特尼筛无限列表

java - 在Java中递归地将数组中的对象与另一个对象相乘

recursion - Clojure 中的非尾递归匿名函数

c - 链表:读取C中的字符串