﻿ Reverse a linked list ~ Programming Tutorials by SourceTricks
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;
};

class List {
public:
List() { head = NULL; }
~List() {}
void reverse();
void print();

private:
};

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

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

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

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

// Test program
int main() {
List* list = new List();
list->print();
list->reverse();
list->print();
delete list;
}``````

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

Name

Email *

Message *