fork download
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Scanner;
  4.  
  5. class Stack {
  6.  
  7. private int pointer;
  8. private int[] stack;
  9. private int size;
  10.  
  11.  
  12. public Stack() {
  13. this(20);
  14. }
  15.  
  16. public Stack(int capacity) {
  17. size = capacity;
  18. stack = new int[size];
  19. pointer = -1;
  20. }
  21.  
  22. public void push(int element) {
  23. stack[++pointer] = element;
  24. }
  25.  
  26. public int pop() {
  27. int i = stack[pointer];
  28. stack[pointer--] = 0;
  29. return i;
  30. }
  31.  
  32. public int back() {
  33. return stack[pointer];
  34. }
  35.  
  36. public void clear() {
  37. Arrays.fill(stack, 0);
  38. pointer = -1;
  39. }
  40.  
  41. public boolean isEmpty() {
  42. if (pointer < 0)
  43. return true;
  44. else
  45. return false;
  46. }
  47.  
  48. public int size() {
  49. return this.pointer + 1;
  50. }
  51.  
  52. public static void main(String[] args) {
  53. Stack stack = new Stack();
  54.  
  55. Scanner scanner = new Scanner(System.in);
  56. System.out.println("enter your command");
  57. String command = scanner.nextLine();
  58.  
  59. while (!command.equals("exit")) {
  60. if (command.matches("^push [0-9]")) {
  61. String[] comm = command.split(" ");
  62. stack.push(Integer.parseInt(comm[1]));
  63. System.out.println("OK");
  64. } else if (command.equals("pop")) {
  65. if (stack.isEmpty()) {
  66. System.out.println("Error. Stack is empty");
  67. } else {
  68. System.out.println(stack.pop());
  69. }
  70. } else if (command.equals("size")) {
  71. System.out.println(stack.size());
  72. } else if (command.equals("back")) {
  73. if (stack.isEmpty()) {
  74. System.out.println("Error. Stack is empty");
  75. } else {
  76. System.out.println(stack.back());
  77. }
  78. } else if (command.equals("clear")) {
  79. stack.clear();
  80. System.out.println("OK");
  81. } else {
  82. System.out.println("Command doesn't exist");
  83. }
  84. command = scanner.nextLine();
  85. }
  86. System.out.println("bye");
  87.  
  88. }
  89. }
  90.  
Success #stdin #stdout 0.06s 711680KB
stdin
push 8
push 4
size
pop
back
push 8
push 7
clear
size
exit
stdout
enter your command
OK
OK
2
4
8
OK
OK
OK
0
bye