Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. /*
  2. Program:- Reverse Stack using recursion
  3. */
  4. #include "stdio.h"
  5. #include "stdlib.h"
  6. #include "string.h"
  7. struct node{
  8. int data;
  9. struct node *next;
  10. };
  11.  
  12. void push(struct node **head,int value)
  13. {
  14. struct node *temp=(struct node*)malloc(sizeof(struct node));
  15. if(temp==NULL)
  16. {
  17. printf("Insufficient memory\n");
  18. return ;
  19. }
  20. temp->data=value;
  21. temp->next=*head;
  22.  
  23. *head = temp;
  24.  
  25. return;
  26.  
  27. }
  28.  
  29. int pop(struct node **head)
  30. {
  31. int element;
  32. struct node *temp=*head;
  33. if (*head == NULL)
  34. {
  35. printf("Stack empty\n");
  36. return;
  37. }
  38. else
  39. {
  40. element=temp->data;
  41. *head=temp->next;
  42. free(temp);
  43. //printf("Popped element: %d\n",element);
  44. return element;
  45. }
  46.  
  47. }
  48. int isEmpty(struct node *head)
  49. {
  50. if(head==NULL)
  51. return 1;
  52. else
  53. return 0;
  54. }
  55.  
  56. void reverse(struct node **head)
  57. {
  58. if(!isEmpty(*head))
  59. {
  60. int temp=pop(head);
  61. reverse(head);
  62. insertAtBottom(head,temp);
  63. }
  64. //printf("Reversed\n");
  65. }
  66.  
  67. void insertAtBottom(struct node **head,int value)
  68. {
  69. if(isEmpty(*head))
  70. {
  71. //printf("Empty stack: %d\n",value);
  72. push(head,value);
  73. }
  74. else
  75. {
  76. int temp=pop(head);
  77. insertAtBottom(head,value);
  78. push(head,temp);
  79. }
  80. }
  81.  
  82. void display(struct node *head)
  83. {
  84. struct node *temp=head;
  85. while(temp!=NULL)
  86. {
  87. printf("%d ", temp->data);
  88. temp=temp->next;
  89. }
  90. printf("\n");
  91.  
  92. }
  93.  
  94. int main()
  95. {
  96. struct node *stack=NULL;
  97. int value,test,answer,choice;
  98. printf("Press 1 to push \nEnter 2 to Reverse\nEnter 3 to display\nEnter 4 to exit\n");
  99. while(1)
  100. {
  101. printf("Enter your choice: ");
  102. scanf("%d",&choice);
  103. switch(choice)
  104. {
  105. case 1:
  106. printf("Enter number to insert: ");
  107. scanf("%d",&value);
  108. push(&stack, value);
  109. break;
  110. case 2:
  111. reverse(&stack);
  112. break;
  113. case 3:
  114. display(stack);
  115. break;
  116. case 4:
  117. exit(0);
  118. break;
  119. default:
  120. printf("Wrong choice\n");
  121. break;
  122. }
  123. }
  124. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement