Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. public class Pilha {
  2.  
  3. private int[] pilha;
  4. private int capacidade;
  5. private int topo;
  6.  
  7. public Pilha(int capacidade) {
  8. this.capacidade = capacidade;
  9. this.topo = -1;
  10. this.pilha = new int[capacidade];
  11. }
  12.  
  13. public boolean isEmpty() {
  14. return this.topo == -1;
  15. }
  16.  
  17. public boolean isFull() {
  18. return this.topo == (capacidade - 1);
  19. }
  20.  
  21. public void push(int n) {
  22.  
  23. if (this.isFull())
  24. throw new RuntimeException("FullStackException");
  25. this.topo += 1;
  26. this.pilha[topo] = n;
  27. }
  28.  
  29. public int pop() {
  30. if (this.isEmpty())
  31. throw new RuntimeException("EmptyStackException");
  32. int valor_topo = this.pilha[topo];
  33. topo -= 1;
  34. return valor_topo;
  35. }
  36.  
  37. public int peek() {
  38. if (this.isEmpty())
  39. throw new RuntimeException("EmptyStackException");
  40. return this.pilha[topo];
  41. }
  42.  
  43. public int size() {
  44. return this.topo + 1;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Pilha pilha = new Pilha(5);
  49. assert pilha.isEmpty();
  50. assert !pilha.isFull();
  51. assert pilha.size() == 0;
  52.  
  53. pilha.push(10);
  54. assert pilha.peek() == 10;
  55. assert pilha.size() == 1;
  56. assert !pilha.isEmpty();
  57.  
  58. pilha.push(5);
  59. assert pilha.size() == 2;
  60.  
  61. assert pilha.pop() == 5;
  62.  
  63. pilha.push(7);
  64. assert pilha.peek() == 7;
  65. pilha.pop();
  66.  
  67. assert !pilha.isEmpty();
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement