Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. import java.util.*;
  2. public class Stack2{
  3. private int[] stack;
  4. private int size;
  5.  
  6. public Stack2(){
  7. stack = new int[10];
  8. size = 0;
  9. }
  10.  
  11. public Stack2(int height){
  12. if(height <= 0){
  13. throw new EmptyStackException();
  14. }
  15. stack = new int[height];
  16. size = 0;
  17. }
  18.  
  19. public void add(int value){
  20. if (size == stack.length){
  21. throw new StackOverflowException();
  22. }
  23. stack[size] = value;
  24. size++;
  25. }
  26.  
  27.  
  28. public int pop(){
  29. if(size == 0){
  30. throw new EmptyStackException();
  31. }
  32. size--;
  33. return stack[size + 1];
  34. }
  35.  
  36. public int peek(){
  37. if(size == 0){
  38. throw new EmptyStackException();
  39. }
  40. return stack[size - 1];
  41. }
  42.  
  43. public boolean isEmpty(){
  44. if(size == 0){
  45. return true;
  46. }
  47. return false;
  48. }
  49.  
  50. public int getSize(){
  51. return this.size;
  52. }
  53.  
  54. class StackOverflowException extends RuntimeException{
  55. public StackOverflowException(){
  56. super("Nothing can be added to the stack. The stack was full and has overflowed");
  57. }
  58.  
  59. public StackOverflowException(String message){
  60. super(message);
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement