Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. package eg.edu.alexu.csd.datastructure.stack;
  2.  
  3. public class Stack implements IStack {
  4. int capacity = 2;
  5. Object[] stack = new Object[capacity];
  6. int top = 0;
  7.  
  8. public int size() {
  9. return top;
  10. }
  11.  
  12. public void push(Object element) {
  13. if (size() == capacity)
  14. expand();
  15.  
  16. stack[top] = element;
  17. top++;
  18.  
  19. }
  20.  
  21. private void expand() {
  22. int length = size();
  23. Object newstack[] = new Object[capacity * 2];
  24. System.arraycopy(stack, 0, newstack, 0, length);
  25. stack = newstack;
  26. capacity *= 2;
  27. }
  28.  
  29. public Object pop() {
  30. if (isEmpty()) {
  31. System.out.println("Stack is Empty!");
  32. return null;
  33. } else {
  34. Object data = stack[top - 1];
  35. stack[top - 1] = 0;
  36. top--;
  37. return data;
  38. }
  39. }
  40.  
  41. public Object peek() {
  42. if(isEmpty()) {
  43. return null;
  44. }
  45. else {
  46. Object data = stack[top - 1];
  47. top--;
  48. return data;
  49. }
  50. }
  51.  
  52. public boolean isEmpty() {
  53. if (size() == 0)
  54. return true;
  55. else
  56. return false;
  57. }
  58.  
  59. public void show() {
  60. for (Object n : stack) {
  61. System.out.println( n);
  62.  
  63. }
  64.  
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement