fork download
#include <iostream>
using namespace std;

// creating node
struct Node {
    int data;
    struct Node* next;
    Node(int data)
    {
        this->data = data;
        next = NULL;
    }
};

struct LinkedList {
    Node* head;
    LinkedList() { head = NULL; }

    // created a function to reverse a linked list 
    void reverse()
    {
        // we are Initializing  current, previous and next pointers
        Node* current = head;
        Node *prev = NULL, *next = NULL;

        while (current != NULL) {
            next = current->next;
            current->next = prev;
            prev = current;
            current = next;
        }
        head = prev;
    }

    // now created a function to print the output 
    void print()
    {
        struct Node* temp = head;
        while (temp != NULL) {
            cout << temp->data << " ";
            temp = temp->next;
        }
    }

    void push(int data)
    {
        Node* temp = new Node(data);
        temp->next = head;
        head = temp;
    }
};

int main()
{
    LinkedList ab;
    ab.push(5);
    ab.push(10);
    ab.push(15);
    ab.push(25);

    cout << "Given linked list is :\n";
    ab.print();

    ab.reverse();

    cout << "\nReversed linked list is : \n";
    ab.print();
    return 0;
}
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Given linked list is :
25 15 10 5 
Reversed linked list is : 
5 10 15 25