Naman Jain
Naman Jain

Reputation: 335

Reverse linked list using double pointer

How to reverse linked list using double pointer?

I was learning about double pointers and thought if we can reverse linked list using one pointer only.

Upvotes: 2

Views: 242

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490098

Conversion to using a pointer to pointer left as an exercise for the reader. Also has some distinct shortcomings in terms of style.

#include <iostream>

struct node { 
    int data;
    node *next;
};

node *reverse(node *list) { 
    node *prev = NULL;
    node *next;

    while (list) {
        next = list->next;
        list->next = prev;
        prev = list;
        list = next;
    }
    return prev;
}

void show_list(node *list) {
    while (list != NULL) {
        std::cout << list->data << ", ";
        list = list->next;
    }
}

int main() {
    node *list = NULL;

    for (int i=0; i<10; i++) {
        node *n = new node;
        n->next = list;
        n->data = i;
        list = n;
    }

    std::cout << "As built: ";
    show_list(list);

    list = reverse(list);

    std::cout << "Reversed: ";
    show_list(list);
    return 0;
}

If you decide to modify a pointer you received as a parameter, it's probably easier to deal with a reference to a pointer than a pointer to a pointer though.

Upvotes: 1

Related Questions