Advertisement
Guest User

Untitled

a guest
Apr 15th, 2014
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. package stackdemo;
  2.  
  3. public class ArrayStackDemo {
  4.  
  5. //Demo
  6. public static void main(String args[]) {
  7. StackInt demoStack = new StackInt();
  8. for (int i = 0; i < demoStack.size(); i++) {
  9. demoStack.push(i);
  10. System.out.println(demoStack.pop());
  11. }
  12. }
  13. }
  14.  
  15. package stackdemo;
  16. import java.util.Arrays;
  17. import java.util.EmptyStackException;
  18.  
  19. public class StackInt {
  20. //Instance variables
  21. private int[] numberStack;
  22. int topOfStack = -1; //Empty stack
  23. private int capacity;
  24. private final int INITIAL_CAPACITY = 10;
  25.  
  26. //Default constructer
  27. public StackInt() {
  28. capacity = INITIAL_CAPACITY;
  29. numberStack = new int[capacity];
  30. }
  31.  
  32. //Size method
  33. public int size() {
  34. return capacity;
  35. }
  36.  
  37. //Empty method
  38. public boolean empty() {
  39. if (topOfStack == -1) {
  40. return true;
  41. }
  42. return false;
  43. }
  44.  
  45. //Push method
  46. public int push(int obj) {
  47. if (topOfStack == numberStack.length - 1) {
  48. reallocate();
  49. }
  50. topOfStack++;
  51. numberStack[topOfStack] = obj;
  52. return obj;
  53. }
  54.  
  55. //Reallocate method
  56. public void reallocate() {
  57. capacity = 2 * capacity;
  58. numberStack = Arrays.copyOf(numberStack, capacity);
  59. }
  60.  
  61. //Pop method
  62. public int pop() {
  63. if (empty()) {
  64. throw new EmptyStackException();
  65. }
  66. return numberStack[topOfStack--];
  67. }
  68.  
  69. //Peek method
  70. public int peek() {
  71. if (empty()) {
  72. throw new EmptyStackException();
  73. }
  74. return numberStack[topOfStack];
  75. }
  76. }
  77.  
  78. src/
  79. stackdemo/
  80. ArrayStackDemo.java
  81. StackInt.java
  82. bin/
  83.  
  84. javac -s src -d bin src/stackdemo/*.java
  85.  
  86. bin/
  87. stackdemo/
  88. ArrayStackDemo.class
  89. StackInt.class
  90.  
  91. java -cp bin stackdemo.ArrayStackDemo
  92.  
  93. java -cp . stackdemo.ArrayStackDemo
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement