Reverse a linked list - Iterative method

Reverse a linked list - Iterative method

Instructor-svgAl-Mamun Sarkar
Apr 16 , 2020

Reverse a linked list - Iterative method. The following c++ code shows how to print a linked list in reverse order.

 

Code:

#include<iostream>
using namespace std;

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

Node *head;

// Ia an item to Link list
void Insert(int x, int p)
{
    Node *temp = new Node();
    temp->data = x;
    temp->next = NULL;

    if (p == 1) {
        temp->next = head;
        head = temp;
        return;
    }

    Node *temp1 = head;

    for (int i=0; i<p-2; i++) {
        temp1 = temp1->next;
    }
    temp->next = temp1->next;
    temp1->next = temp;

}


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


// Reverse link list
void Reverse()
{
    Node *current, *pre, *next;
    current = head;
    pre = NULL;

    while (current != NULL) {
        next = current->next;
        current->next = pre;
        pre = current;
        current = next;
    }
    head = pre;
}


int main()
{
    head = NULL;
    cout << "How many numbers : ";
    int n, x, p;

    cin >> n;

    for (int i=0; i<n; i++) {
        cout << "Enter the number " << endl;
        cin >> x >> p;
        Insert(x, p);
        Print();
    }

    Reverse();

    cout << "Print after Reverse : " << endl;
    Print();

    return 0;
}

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram