Question #236731

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 List {
    int item;
    struct List* nextNode;
    List(int data)
    {
        this->item = data;
        nextNode = NULL;
    }
};
 
struct LinkedList {
    List* head;
    LinkedList() { head = NULL; }
 
    void reverseList()
    {
        
        List* current = head;
        List *prev = NULL, *next = NULL;
 
        while (current != NULL) {
            
            next = current->nextNode;
 
            
            current->nextNode= prev;
 
            
            prev = current;
            current = next;
        }
        head = prev;
    }
 
    
    void printList()
    {
        struct List* temp = head;
        while (temp != NULL) {
            cout << temp->item << " ";
            temp = temp->nextNode;
        }
    }
 
    void push(int data)
    {
        List* temp = new List(data);
        temp->nextNode = head;
        head = temp;
    }
};
 
//Testing code
int main()
{
  
    LinkedList list;
    list.push(10);
    list.push(20);
    list.push(30);
    list.push(40);
    list.push(50);
 
    cout << "Before reversing the linked list\n";
    list.printList();
 
    list.reverseList();
 
    cout << "\nAfter reversing the Linked list \n";
    list.printList();
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS