Answer to Question #235851 in C++ for Huma

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.
1
Expert's answer
2021-09-13T18:38:44-0400
#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;
}

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