使用单链表反转字符串

时间:2019-05-07 08:41:46

标签: c++ data-structures

我正在尝试使用链表打印字符串的反面。假设我的字符串是“世界充满了好人”,则应打印“人民充满了好人是世界”

#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;
}

因此,如果字符串为“世界上充满了好人”,则预期输出为 “人的充实就是世界”,从而扭转了节点。但是正在获得“世界”作为输出

2 个答案:

答案 0 :(得分:2)

因此反转列表不是问题,请确保您按值传递了head,因此您实际上是在更改head的副本。有关更多信息,请查看pass by value vs pass by reference

解决问题的方法是将原型更改为void reverseList(node **head),随后必须使用head来引用*head的每个后续访问。

最后,用reverseList(&head);

调用函数

答案 1 :(得分:1)

void reverseList(node *head)-在这里,您将更新按值传递的临时head

将函数声明更改为 void reverseList(node*& head)