DEV Community

Divyanshu Singh
Divyanshu Singh

Posted on

reversing a linked list

#include <iostream>
using namespace std;
struct Node
{
    int data;
    Node* next;
};
Node* head;
void insertAtNthPosition(int x, int pos)
{

   Node* temp1 = new Node();
   temp1->data = x;
   if(pos == 1)
   {
       temp1->next = head;
       head = temp1;
       return;
   }
   temp1->next = NULL;
   Node* temp2 = head;
   for(int i = 0; i<pos-2; i++)
   {
       if(temp2 == NULL)
       {
           cout<< "INVALID POSITION\n";
           return;
       }
       temp2 = temp2->next;
    }
    if(temp2 == NULL)
       {
           cout<< "INVALID POSITION\n";
           return;
       }  
    temp1->next = temp2->next;
    temp2->next = temp1;
}
void print()
{
    Node* temp = head;
    cout<<"The list:\n";
    while(temp != NULL)
    {
        cout<< temp->data << " ";
        temp = temp->next;
    }
    cout<< endl;
}
void reverse()
{
    Node* prev = NULL;
    Node* current = head;
    Node* next;
    while(current != NULL)
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    head = prev;
}
int main()
{
    head = NULL;
    int n, pos, x;
    cout << "How many elements do you want to insert and at a random position?\n";
    cin>>n;
    for(int i = 0; i<n; i++)
    {
    cout<< "Enter the element and the position of the element\n";
    cin>>x>>pos;
    insertAtNthPosition(x,pos);
    print();
    }
    cout<< "The reversed list is:\n";
    reverse();
    print();
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)