Tuesday, July 10, 2012

Write a program to construct and reverse a linked list

We write an iterative approach to reverse a linked list. The approach is to start from the head node and prep-end the subsequent nodes so that the list gets reversed. 3 pointers are used to do the list manipulation.

C++ program to reverse a linked list

#include <iostream>
using namespace std;

// List nodeclass
class Node {
public:
    int data;
    Node* next;
};

// Linked list class
class List {
public:
    List() { head = NULL; }
    ~List() {}
    void addNode(int val);
    void reverse();
    void print();

private:
    Node* head;
};

// Function to add a node to the list
void List::addNode(int val)
{
    Node* temp = new Node();
    temp->data = val;
    temp->next = NULL;

    if ( head == NULL ) {
        head = temp;
    }
    else {
        Node* temp1 = head;
        while ( temp1->next != NULL )
            temp1 = temp1->next;
        temp1->next = temp;
    }
}

// Iterative function to reverse a list
void List::reverse()
{
    Node* n1 = head;
    Node* n2 = NULL;
    Node* n3 = NULL;
    while ( n1 != NULL )
    {
        head = n1;
        n2 = n1->next;
        n1->next = n3;
        n3 = n1;
        n1 = n2;
    }
}

void List::print()
{
    Node* temp = head;
    while ( temp != NULL ) {
        cout << temp->data << " ";         
        temp = temp->next;
    }
    cout << endl; 
} 

// Test program 
int main() {    
    List* list = new List();     
    list->addNode(100);
    list->addNode(200);
    list->addNode(300);
    list->addNode(400);
    list->addNode(500);
    list->print();
    list->reverse();
    list->print();
    delete list;
}


Output:-
100 200 300 400 500
500 400 300 200 100

Contact Form

Name

Email *

Message *

Back to Top