#include <iostream>
using namespace std;
struct stack
{
int data;
struct stack *next;
};
typedef struct stack node;
node *head=NULL,*rev_head=NULL;
int count=0;
int call=1;
node *stack_push(node *&head, int a)
{
node *temp=new node();
temp->data=a;
temp->next = NULL;
if(head==NULL)
{
head = temp;
}
else
{
node *last = head;
while(last->next!=NULL)
{
last = last ->next;
}
last -> next = temp;
}
return head;
}
int stack_pop(node *&head)
{
int pop;
if(head==NULL)
{
cout<<"Stack is Empty "<<endl;
return 0;
}
node *temp=head;
if(count == 1)
{
temp = head->next;
pop=head->data;
delete(head);
head=temp;
count--;
}
else
{
int i=1;
while(i != count-1)
{
temp = temp->next;
i++;
}
pop=temp->next->data;
delete(temp->next);
count--;
}
return pop;
}
int menu()
{
while(1)
{
int flag;
cout<<"Press 1 for PUSH
2 for POP
3 for Exit."<<endl;
cin>>flag;
if(flag==1)
{
cout<<"Data: ";
int a;
cin>>a;
count++;
head = stack_push(head,a);
}
if(flag==2)
{
stack_pop(head);
}
if(flag == 3) return 0;
}
}
void print(node *head)
{
node *temp = head;
if(head==NULL)
{
cout<<"
No Data Found
";
}
else
{
cout<<"Your Linked List: ";
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
cout<<endl;
}
void rev(node *&temp, node *&rev_head)
{
if(temp == NULL)
{
return;
}
else
{
int a = stack_pop(head);
rev_head = stack_push(rev_head,a);
rev(temp->next,rev_head);
}
}
int main()
{
menu();
print(head);
rev(head,rev_head);
print(rev_head);
return 0;
}
Output
Press 1 for PUSH
2 for POP
3 for Exit.
1
Data: 1
Press 1 for PUSH
2 for POP
3 for Exit.
1
Data: 1
Press 1 for PUSH
2 for POP
3 for Exit.
1
Data: 2
Press 1 for PUSH
2 for POP
3 for Exit.
1
Data: 3
Press 1 for PUSH
2 for POP
3 for Exit.
3
Your Linked List: 1 1 2 3
Add your comment