Reverse a linked list

PHOTO EMBED

Sun Sep 11 2022 08:46:27 GMT+0000 (Coordinated Universal Time)

Saved by @Surajverma #c++

#include<bits/stdc++.h>
using namespace std;


struct Node{
    int data;
    struct Node *next;
    Node(int data){
        this->data = data;
        next = NULL;
    }
};
    
    
struct LinkedList {
    
    Node *head;
    LinkedList() { head = NULL;}
    
    
    void reverse()
    {
        Node *current = head;
        Node *prev = NULL;
        Node *next = NULL;
        
        while(current != NULL) {
            next = current->next;
            current-> next = prev;
            prev = current;
            current = next;
        }
        head = prev;
    }
    
    
    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 ll;
    ll.push(1);
    ll.push(2);
    ll.push(3);
    ll.push(4);
    
    
    ll.print();
    cout << endl;
    
    ll.reverse();
    ll.print();
    
    return 0;
}
content_copyCOPY