Advertisement
Guest User

Untitled

a guest
Feb 29th, 2020
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. char menu()
  4. {
  5. char choice;
  6. cout << "Menu \n";
  7. cout << "1. Add an element \n";
  8. cout << "2. Remove an element \n";
  9. cout << "3. Show the stack \n";
  10. cout << "4. Exit\n";
  11. cin >> choice;
  12. return choice;
  13. }
  14. int StrToInt(string b)
  15. {
  16. int l, M;
  17. l = b.length();
  18. M = 0;
  19. for (int i = 0; i < l; i++)
  20. {
  21. M += (b[i] - '0') * pow(10, l - i - 1);
  22. }
  23. return M;
  24. }
  25. struct stack {
  26. int data;
  27. struct stack* next;
  28. };
  29. void s_push(stack** top, int D) {
  30. stack* node;
  31. node = new stack();
  32. node->data = D;
  33. if (top == NULL) {
  34. *top = node;
  35. }
  36. else
  37. {
  38. node->next = *top;
  39. *top = node;
  40. }
  41. }
  42. void s_print(stack* top) {
  43. stack* node = top;
  44. if (top == NULL)
  45. {
  46. cout << "The stack is empty \n";
  47. }
  48. else
  49. {
  50. cout << "The stack consists : \n";
  51. while (node) {
  52. cout << node->data << " ";
  53. node = node->next;
  54. }
  55. }
  56. }
  57. void s_delete_key(stack** top,int p) {
  58. if (p <= 0)
  59. {
  60. cout << "You`re idiot!!! The stack is empty\n";
  61. }
  62. else
  63. {
  64. stack* node = *top;
  65. *top = node->next;
  66. free(node);
  67. node->data = NULL;
  68. node->next = NULL;
  69. cout << "The top element is deleted \n";
  70. }
  71. }
  72. int main()
  73. {
  74. stack* top = NULL;
  75. char choice;
  76. string number;
  77. int num=0,p=0;
  78. do {
  79. metka:
  80. choice = menu();
  81. switch (choice)
  82. {
  83. case '1':
  84. cout << "Input an element :";
  85. cin >> number;
  86. for (auto c : number)
  87. {
  88. if (c >= '0' && c <= '9')
  89. {
  90. num = StrToInt(number);
  91. }
  92. else
  93. goto metka;
  94. }
  95. cout << endl;
  96. s_push(&top, num);
  97. cout << "The element is added \n";
  98. p++;
  99. break;
  100. case '2':
  101. s_delete_key(&top,p);
  102. p--;
  103. break;
  104. case '3':
  105. s_print(top);
  106. cout << endl;
  107. break;
  108. default: cout << "System exit\n";
  109. }
  110. } while (choice != '4');
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement