fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3. struct Stack {
  4. int data;
  5. struct Stack *next;
  6. };
  7.  
  8. struct Stack *newNode(int data){
  9. struct Stack *stackNode = (Stack*)malloc(sizeof(Stack));
  10. stackNode->data = data;
  11. stackNode->next = NULL;
  12. return stackNode;
  13. }
  14.  
  15. void push(struct Stack **root,int data){
  16. Stack *stack = newNode(data);
  17. stack->next = *root;
  18. *root = stack;
  19. }
  20.  
  21. bool isEmpty(struct Stack *root ){
  22. return !root;
  23. }
  24.  
  25. int pop(Stack **root){
  26. if(isEmpty(*root)){
  27. cout<<"STACK UNDERFLOW";
  28. }
  29. else{
  30. Stack *temp = *root;
  31. *root = (*root)->next;
  32. int popped = temp->data;
  33. free(temp);
  34. return popped;
  35. printf("yes");
  36. }
  37. }
  38.  
  39. void print(Stack *root){
  40. while(root!= NULL){
  41. printf("%d", root->data);
  42. root = root->next;
  43. }
  44. }
  45. void InsertBottom(struct Stack **root, int item){
  46. if(isEmpty(*root) || item <(*root)->data){
  47. push(root,item);
  48. }
  49. else{
  50. int temp = pop(root);
  51. InsertBottom(root,item);
  52.  
  53. push(root,temp);
  54.  
  55. }
  56.  
  57. }
  58. void reverse(struct Stack **root){
  59. if(!isEmpty(*root)){
  60. int temp = pop(root);
  61. reverse(root);
  62. InsertBottom(root,temp);
  63.  
  64. }
  65. }
  66.  
  67.  
  68. int main() {
  69. // your code goes here
  70. struct Stack *root = NULL;
  71. push(&root,5);
  72. push(&root,7);
  73. push(&root,1);
  74. push(&root,2);
  75. reverse(&root);
  76. print(root);
  77. return 0;
  78. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
1257