Advertisement
Guest User

Untitled

a guest
Feb 28th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node
  4. {
  5. int data;
  6. int n;
  7. struct node *next;
  8. };
  9. struct node *heada=(struct node *) malloc (sizeof(struct node)), *headb=(struct node *) malloc (sizeof(struct node)), *headc=(struct node *) malloc (sizeof(struct node));
  10.  
  11. void push(struct node *ptr, int i);
  12. int pop(struct node *ptr);
  13. void display(struct node *ptr);
  14. void Move(int n, struct node *org, struct node *med, struct node *des);
  15. int main()
  16. {
  17. heada->next=NULL; headb->next=NULL; headc->next=NULL;
  18. int n;
  19. cin>>n;
  20. for (int i=n;i>=1;i--)
  21. {
  22. push(heada,i);
  23. }
  24. display(heada);
  25. //pop(heada);
  26. Move(n,heada,headb,headc);
  27. display(headc);
  28. }
  29. void push(struct node *ptr,int i)
  30. {
  31. struct node *newnode=(struct node*) malloc (sizeof(struct node));
  32. newnode->data=i;
  33. if (ptr==heada)
  34. {
  35. newnode->next=ptr;
  36. //ptr->next=NULL;
  37. heada=newnode;
  38. cout<<"Pushing into A\n";
  39. //display(heada);
  40. }
  41. else if (ptr==headb)
  42. {
  43. newnode->next=ptr;
  44. //ptr->next=NULL;
  45. headb=newnode;
  46. cout<<"Pushing into B\n";
  47. //display(headb);
  48. }
  49. else if (ptr==headc)
  50. {
  51. newnode->next=ptr;
  52. //ptr->next=NULL;
  53. headc=newnode;
  54. cout<<"Pushing into C\n";
  55. //display(headc);
  56. }
  57. //cout<<"Successfully pushed "<<newnode->data<<endl;
  58. //newnode->next=NULL;
  59. }
  60. int pop(struct node *ptr)
  61. {
  62. int x;
  63. struct node *pre;
  64. if (ptr==heada)
  65. {
  66. x=ptr->data;
  67. pre=ptr->next;
  68. heada=pre;
  69. cout<<"Popping from A "<<x<<endl;
  70. }
  71. else if (ptr==headb)
  72. {
  73. x=ptr->data;
  74. pre=ptr->next;
  75. headb=pre;
  76. cout<<"Popping from B "<<x<<endl;
  77. }
  78. else if (ptr==headc)
  79. {
  80. x=ptr->data;
  81. pre=ptr->next;
  82. headc=pre;
  83. cout<<"Popping from C "<<x<<endl;
  84. }
  85. free(ptr);
  86. return x;
  87. }
  88. void display(struct node *ptr)
  89. {
  90. if (ptr==NULL)
  91. cout<<"Stack is empty"<<endl;
  92. while(ptr->next!=NULL)
  93. {
  94. cout<<ptr->data<<endl;
  95. ptr=ptr->next;
  96. }
  97. }
  98. void Move(int n, struct node *org, struct node *med, struct node *des)
  99. {
  100. if (n>0)
  101. {
  102. Move(n-1,org,des,med);
  103. push(des,pop(org));
  104. Move(n-1,med,org,des);
  105. }
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement