Question #235851

The Linked List contains certain Nodes containing data of integer type, You cannot use any
other type of Array or data structure neither doubly Linked List. Use only singly linked list,
Implement a function which can reverse the List. Write down the code take dummy data to
test and take snap shot to show output paste it in document.

Expert's answer

#include <iostream>
using namespace std;
struct Node {
    int info;
    struct Node* next;
    Node(int info)
    {
        this->info = info;
        next = NULL;
    }
};
 
struct LinkedList {
    Node* head;
    LinkedList() { head = NULL; }
    void reverse()
    {
        Node* cur = head;
        Node *prev = NULL, *next = NULL;
 
        while (cur != NULL) {
            next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        head = prev;
    }
    void display()
    {
        struct Node* temp = head;
        while (temp != NULL) {
            cout << temp->info << " ";
            temp = temp->next;
        }
    }
 
    void push(int info)
    {
        Node* temp = new Node(info);
        temp->next = head;
        head = temp;
    }
};
int main()
{
    LinkedList List;
    List.push(15);
    List.push(6);
    List.push(10);
    List.push(20);
    cout << "Initial linked list\n";
    List.display();
    List.reverse();
    cout << "\nReversed Linked list \n";
    List.display();
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS