Advertisement
raffaelegriecoit

Stack

Jun 13th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. class MyStack {
  2.  
  3. int[] stack;
  4. int top;
  5.  
  6. public MyStack() {
  7. stack = new int[5];
  8. top = -1;
  9. }
  10.  
  11. public void push(int x) {
  12. if(top < stack.length-1){
  13. top++;
  14. stack[top] = x;
  15. }
  16. else{
  17. System.out.println("The stack is full");
  18. }
  19. }
  20.  
  21. public int pop() {
  22. if(top >= 0){
  23. int elemento = stack[top];
  24. top--;
  25. return elemento;
  26. }
  27. else{
  28. System.out.println("The stack is empty");
  29. return -1;
  30. }
  31. }
  32.  
  33. public int top() {
  34. if (top >= 0) {
  35. return stack[top];
  36. }
  37. else {
  38. System.out.println("The stack is empty");
  39. return -1;
  40. }
  41. }
  42.  
  43. public boolean empty() {
  44. if(top < 0){
  45. return true;
  46. }
  47. else{
  48. return false;
  49. }
  50. }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement