How to reverse a singly linked list in-place in C++

1 Answer

0 votes
#include <iostream>

// Node structure for singly linked list
struct Node {
    int data;        // value stored in the node
    Node* next;      // pointer to the next node

    Node(int val) : data(val), next(nullptr) {}
};

// Reverse the linked list in-place
Node* reverseList(Node* head) {
    Node* prev = nullptr;      // will become the new head
    Node* current = head;      // pointer to traverse the list
    Node* next = nullptr;      // temporary pointer to store next node

    while (current != nullptr) {
        next = current->next;   // save next node
        current->next = prev;   // reverse the link
        prev = current;         // move prev forward
        current = next;         // move current forward
    }

    return prev; // prev is the new head after full reversal
}

// Print the linked list
void printList(Node* head) {
    Node* temp = head;
    while (temp != nullptr) {
        std::cout << temp->data;
        if (temp->next != nullptr) std::cout << " -> ";
        temp = temp->next;
    }
    std::cout << std::endl;
}

int main() {
    // Create a sample list: 1 -> 2 -> 3 -> 4 -> 5
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);

    std::cout << "Original list:\n";
    printList(head);

    // Reverse the list
    head = reverseList(head);

    std::cout << "Reversed list:\n";
    printList(head);
}



/*
run:

Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1

*/

 



answered 5 days ago by avibootz
...