Answer to Question #236731 in C++ for Bill

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.
1
Expert's answer
2021-09-13T12:18:36-0400


#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS