Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct node
- {
- int data;
- int n;
- struct node *next;
- };
- struct node *heada=(struct node *) malloc (sizeof(struct node)), *headb=(struct node *) malloc (sizeof(struct node)), *headc=(struct node *) malloc (sizeof(struct node));
- void push(struct node *ptr, int i);
- int pop(struct node *ptr);
- void display(struct node *ptr);
- void Move(int n, struct node *org, struct node *med, struct node *des);
- int main()
- {
- heada->next=NULL; headb->next=NULL; headc->next=NULL;
- int n;
- cin>>n;
- for (int i=n;i>=1;i--)
- {
- push(heada,i);
- }
- display(heada);
- //pop(heada);
- Move(n,heada,headb,headc);
- display(headc);
- }
- void push(struct node *ptr,int i)
- {
- struct node *newnode=(struct node*) malloc (sizeof(struct node));
- newnode->data=i;
- if (ptr==heada)
- {
- newnode->next=ptr;
- //ptr->next=NULL;
- heada=newnode;
- cout<<"Pushing into A\n";
- //display(heada);
- }
- else if (ptr==headb)
- {
- newnode->next=ptr;
- //ptr->next=NULL;
- headb=newnode;
- cout<<"Pushing into B\n";
- //display(headb);
- }
- else if (ptr==headc)
- {
- newnode->next=ptr;
- //ptr->next=NULL;
- headc=newnode;
- cout<<"Pushing into C\n";
- //display(headc);
- }
- //cout<<"Successfully pushed "<<newnode->data<<endl;
- //newnode->next=NULL;
- }
- int pop(struct node *ptr)
- {
- int x;
- struct node *pre;
- if (ptr==heada)
- {
- x=ptr->data;
- pre=ptr->next;
- heada=pre;
- cout<<"Popping from A "<<x<<endl;
- }
- else if (ptr==headb)
- {
- x=ptr->data;
- pre=ptr->next;
- headb=pre;
- cout<<"Popping from B "<<x<<endl;
- }
- else if (ptr==headc)
- {
- x=ptr->data;
- pre=ptr->next;
- headc=pre;
- cout<<"Popping from C "<<x<<endl;
- }
- free(ptr);
- return x;
- }
- void display(struct node *ptr)
- {
- if (ptr==NULL)
- cout<<"Stack is empty"<<endl;
- while(ptr->next!=NULL)
- {
- cout<<ptr->data<<endl;
- ptr=ptr->next;
- }
- }
- void Move(int n, struct node *org, struct node *med, struct node *des)
- {
- if (n>0)
- {
- Move(n-1,org,des,med);
- push(des,pop(org));
- Move(n-1,med,org,des);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement