#include <iostream>
using namespace std;
int flag=1;
struct STACK
{
int data;
struct STACK *next;
};
typedef struct STACK stack ;
stack *head=NULL,*new_s=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;
}
int POP()
{
int a;
if(count<=0)
{
cout<<"
Linked List is Empty
";
return 0;
}
else
{
stack *temp = head;
int i=1;
if(count==1)
{
a = head->data; ///save the pop value
head=NULL;
delete(temp);
count--;
}
else
{
while(i != count-1)
{
temp = temp->next;
i++;
}
a = temp->next->data; ///save the pop value
delete(temp->next);
temp->next=NULL;
count--;
}
return a; ///return pop value
}
}
void print(stack *temp)
{
if(temp==NULL)
{
cout<<"
No Data Found
";
}
else
{
cout<<"Your Linked List: ";
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
cout<<endl;
}
void new_stack()
{
if(head==NULL) ///if the main stack is empty
{
return;
}
int a = POP(); ///call the pop function and save the pop value in a
stack *temp =new stack();
temp->data=a;
temp->next =NULL;
if(new_s==NULL) ///create new stack
{
new_s=temp;
}
else
{
stack *last=new_s;
while(last->next!=NULL)
{
last = last->next;
}
last->next = temp;
}
}
void rev( stack *temp) ///revers the stack with recursion
{
if(head==NULL)
{
return;
}
else
{
new_stack(); ///call this function for crate new stack
rev(temp); ///recursive call
}
}
int main()
{
while(flag==1)
{
cout<<"Press 1 to insert 0 to Exit: ";
cin>>flag;
if(flag != 1) break;
PUSH();
}
stack *temp=head;
print(temp);
rev(temp);
print(new_s);
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
Your Linked List: 3 2 1
Add your comment