Solved programming problem

Print a Stack Reverse with Linked List in C++.

Source code

#include <iostream>

using namespace std;

int flag=1;

struct STACK

{

    int data;

    struct STACK *next;

};

typedef struct STACK stack ;

stack *head=NULL;

int count=0;

void PUSH()

{

    stack *temp=new stack();

    cout<<"Data: ";

    cin>>temp->data;

    temp->next=NULL;

    if(head==NULL)

    {

        head=temp;

    }

    else

    {

        stack *last=head;

        while(last->next!=NULL)

        {

            last = last->next;

        }

        last->next=temp;

    }

    count++;

    return;

}

void print(stack *temp)

{

  ///  stack *temp =head;

    if(temp==NULL)

    {

        cout<<"
No Data Found
";

    }

    else

    {

        cout<<"Your Linked List: ";

       while(temp!=NULL)

       {

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

           temp = temp->next;

       }

    }

    cout<<endl;

}

void rev( stack *temp)

{

    if(temp==NULL)

    {

        return;

    }

    else

        {

           rev(temp->next);

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

        }

}

int main()

{

    while(flag==1)

    {

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

        cin>>flag;

        if(flag != 1) break;

        PUSH();

    }

    print(head);

    cout<<"Revers Linked List: ";

    rev(head);

    return 0;

}

Output

Press 1 to insert 0 to Exit: 1
Data: 1
Press 1 to insert 0 to Exit: 1
Data: 2
Press 1 to insert 0 to Exit: 1
Data: 3
Press 1 to insert 0 to Exit: 0
Your Linked List: 1 2 3
Revers Linked List: 3 2 1

Join the discussion

Add your comment