Advertisement
Guest User

cosme

a guest
Feb 18th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. import java.util.*;
  2. public class Stack_Backstrom
  3. {
  4. static int a[] = new int [50];
  5. static int top = -1;
  6. public static void main (String args[])
  7. {
  8. Scanner scanner = new Scanner(System.in);
  9. System.out.println("This program performs various stack operations.");
  10. while(true)
  11. {
  12. System.out.println("Please select one of the numbers below:");
  13. System.out.println("1.Clear - Clears the contents of the stack.");
  14. System.out.println("2.IsEmpty - Returns true if the stack is empty, false if it is not.");
  15. System.out.println("3.IsFull - Returns true if the stack is full, false if it is not.");
  16. System.out.println("4.Push - Adds an item to the top of the stack.");
  17. System.out.println("5.Pop - Removes an item from the top of the stack.");
  18. System.out.println("6.Peek - Returns the value at the top of the stack.");
  19. System.out.println("7.Exit - Exits the program.");
  20. int Choice = scanner.nextInt();
  21.  
  22. switch(Choice)
  23. {
  24. case 1:
  25. top = -1;
  26. break;
  27. case 2:
  28. isempty();
  29. break;
  30. case 3:
  31. isfull();
  32. break;
  33. case 4:
  34. push();
  35. break;
  36. case 5:
  37. pop();
  38. break;
  39. case 6:
  40. peek();
  41. break;
  42. case 7:
  43. System.exit(0);
  44. break;
  45. }
  46. }
  47. }
  48.  
  49. static void isempty()
  50. {
  51. if (top == -1)
  52. System.out.println("true");
  53. else System.out.println("false");
  54. }
  55.  
  56. static void isfull()
  57. {
  58. if(top == 50)
  59. System.out.println("true");
  60. else System.out.println("false");
  61. }
  62.  
  63. static void push()
  64. {
  65. if(top == 50)
  66. System.out.println("Error: Stack is full.");
  67. else
  68. {
  69. top++;
  70. System.out.println("Please enter the value to be added to the top of the stack:");
  71. Scanner scanner = new Scanner(System.in);
  72. int pushval = scanner.nextInt();
  73. a[top] = pushval;
  74. }
  75. }
  76.  
  77. static void pop()
  78. {
  79. if(top == -1)
  80. System.out.println("Error: Stack is empty.");
  81. else
  82. {
  83. int popval = a[top];
  84. top--;
  85. System.out.println("Value" + " " + popval + " " + "has been popped.");
  86. }
  87. }
  88.  
  89. static void peek()
  90. {
  91. if(top == -1)
  92. System.out.println("Error: Stack is empty.");
  93. else
  94. {
  95. System.out.println("The value on top of the stack is:" + a[top]);
  96. }
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement