Solved programming problem

Find The Reverse of a Single Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

int count=0;

typedef struct list node;

node *head=NULL;

void insert_node() ///insert function

{

    node *temp=new node();

    node *last;

    count++; ///for every call,count the total node

    cout<<"Data: ";

    cin>>temp->data;

    temp->next=NULL;

    if(head==NULL)

    {

        head=temp;

    }

    else

    {

        last = head;

        while(last->next != NULL)

        {

            last=last->next;

        }

        last->next=temp;

    }

}

void rev()

{

    node *temp;

    cout<<"
Your Reverse Linked List: ";

    while(count!=0) /// while we don't travel full linked list

    {

        temp=head;

        int i=0; ///temp count

        while(temp != NULL)

        {

            i++;

            if(i==count) ///find the last node by matching count and i

            {

                cout<<temp->data<<" "; ///print

            }

            temp=temp->next;

        }

        count--; ///reduce the count value

    }

    cout<<endl;

}

void  print()

{

    node *temp=head;

    cout<<"
Linked List: ";

    while(temp!=NULL) ///print

    {

        cout<<temp->data<<" ";

        temp=temp->next;

    }

    cout<<endl;

}

int main()

{

    int flag=1;

    while(flag==1)

    {

        insert_node();

        cout<<"Press 1 to insert Data Else 0 to Exit: ";

        cin>>flag;

    }

    print();

    rev();

    return 0;

}

Output

Data: 1
Press 1 to insert Data Else 0 to Exit: 1
Data: 2
Press 1 to insert Data Else 0 to Exit: 1
Data: 3
Press 1 to insert Data Else 0 to Exit: 1
Data: 4
Press 1 to insert Data Else 0 to Exit: 1
Data: 5
Press 1 to insert Data Else 0 to Exit: 0

Linked List: 1 2 3 4 5

Your Reverse Linked List: 5 4 3 2 1

Join the discussion

Add your comment