sushant
sushant

Reputation: 41

reverse a string using singly linked list

i am trying to print the reverse of the string using linked list. suppose my string is "World is full of good people" , it should print "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;
}

So if the string is "World is full of good people", the expected output is "people good of full is world", hence reversing the node. But is getting "World" as output

Upvotes: 0

Views: 1472

Answers (2)

Wander3r
Wander3r

Reputation: 1881

void reverseList(node *head) -- Here you are updating the temporary head which is passed by value.

Change the function declaration to void reverseList(node*& head)

Upvotes: 1

Pratik Sampat
Pratik Sampat

Reputation: 330

So reversing the list is not the problem, See that you passed the head by value So you're essentially making changes to the copy of head. Please have a look at pass by value vs pass by reference for more information on this.

The solution to your problem is to change your prototype to void reverseList(node **head) and each subsequent access of head will have to deferencened using *head.

Lastly, call your function with reverseList(&head);

Upvotes: 3

Related Questions