If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Below is the C++ implementation of the
DoublyLinkedListclass with a method to reverse the doubly linked list:cppCopy code
#include <iostream> class Node { public: int data; Node* next; Node* prev; Node(int data) : data(data), next(nullptr), prev(nullptr) {} }; class DoublyLinkedList { private: Node* head; Node* tail; public: DoublyLinkedList() : head(nullptr), tail(nullptr) {} ~DoublyLinkedList() { Node* current = head; while (current) { Node* temp = current; current = current->next; delete temp; } } void insertAtHead(int data) { Node* newNode = new Node(data); if (!head) { head = newNode; tail = newNode; } else { newNode->next = head; head->prev = newNode; head = newNode; } } void reverse() { if (!head || !head->next) { return; // Empty list or only one node, no need to reverse } Node* current = head; Node* prevNode = nullptr; while (current) { // Swap the "next" and "prev" pointers for the current node Node* nextNode = current->next; current->next = prevNode; current->prev = nextNode; // Move to the next node in the original direction prevNode = current; current = nextNode; } // Swap the head and tail pointers after reversing tail = head; head = prevNode; } void displayForward() { if (!head) { std::cout << "List is empty." << std::endl; return; } Node* current = head; while (current) { std::cout << current->data << " -> "; current = current->next; } std::cout << "NULL" << std::endl; } void displayBackward() { if (!tail) { std::cout << "List is empty." << std::endl; return; } Node* current = tail; while (current) { std::cout << current->data << " -> "; current = current->prev; } std::cout << "NULL" << std::endl; } }; int main() { DoublyLinkedList list; list.insertAtHead(1); list.insertAtHead(2); list.insertAtHead(3); list.insertAtHead(4); list.displayForward(); // Output: 4 -> 3 -> 2 -> 1 -> NULL list.reverse(); list.displayForward(); // Output: 1 -> 2 -> 3 -> 4 -> NULL return 0; }In this implementation, the
reversemethod is added to theDoublyLinkedListclass. This method uses two pointers,currentandprevNode, to reverse the "next" and "prev" pointers of each node iteratively. Once the reversing is complete, theheadandtailpointers are updated to reflect the new positions.In the
mainfunction, we demonstrate how to use theDoublyLinkedListclass by creating a doubly linked list, inserting elements at the head, and then reversing the list using thereversemethod. The output will be4 -> 3 -> 2 -> 1 -> NULLfor the initial list and1 -> 2 -> 3 -> 4 -> NULLafter the reversal.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support