首页 > 解决方案 > 使用单链表反转字符串

问题描述

我正在尝试使用链表打印字符串的反向。假设我的字符串是“World is full of good people”,它应该打印“people good of full is World”

#include <iostream>

using namespace std;
/******** Fucntions Prototype *********/

void printList();


typedef struct Node
{
    string data;
    struct Node *next;
}node;

struct Node* newNode(string userData)
{
    node *temp = new Node;
    temp->data = userData;
    temp->next = NULL;
    return temp;
}

void printList(node* head)
{
    node *temp = head;
    while(temp != NULL)
    {
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}
void reverseList(node *head)
{
    node *curr = head;
    node *prev = NULL, *next = NULL;
    while(curr != NULL)
    {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    head = prev;

}
int main()
{
    node *head = newNode("World");
    head->next = newNode("is");
    head->next->next = newNode("full");
    head->next->next->next = newNode("of");
    head->next->next->next->next = newNode("good");
    head->next->next->next->next->next = newNode("people");
    cout<<"Linked list before reverse is:\n";
    printList(head);
    cout<<"\n";
    reverseList(head);
    cout<<"Linked list after reverse is:\n";
    printList(head);

    return 0;
}

因此,如果字符串是“World is full of good people”,则预期输出是“people good of full is world”,因此节点反转。但是将“世界”作为输出

标签: c++data-structures

解决方案


所以颠倒列表不是问题,看到你传递了head值所以你实际上是在对head. 请查看按值传递与按参考传递以获取更多信息。

您的问题的解决方案是将您的原型更改为, void reverseList(node **head)并且每次后续访问head都必须使用*head.

最后,调用你的函数reverseList(&head);


推荐阅读