Advertisement
Guest User

Untitled

a guest
Dec 16th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. package intStack;
  2.  
  3. public interface Stack {
  4. public void push(int v);
  5. public int pop();
  6. public int top();
  7. public boolean full();
  8. public boolean empty();
  9. }
  10. package fixedStack;
  11.  
  12. public class Stack implements intStack.Stack {
  13. private int[] s;
  14. private int up;
  15. public Stack(int size) {
  16. s = new int[size];
  17. up = -1;
  18. }
  19. public void push(int v) {
  20. s[++up] = v;
  21. }
  22. public int pop() {
  23. return s[up--];
  24. }
  25. public int top() {
  26. return s[up];
  27. }
  28. public boolean full() {
  29. return up == s.length-1;
  30. }
  31. public boolean empty() {
  32. return up == -1;
  33. }
  34. }
  35. package dynStack;
  36.  
  37. public class Stack implements intStack.Stack {
  38. private int[] s;
  39. private int up;
  40. public Stack(int size) {
  41. s = new int[size];
  42. up = -1;
  43. }
  44. public void push(int v) {
  45. s[++up] = v;
  46. }
  47. public int pop() {
  48. return s[up--];
  49. }
  50. public int top() {
  51. return s[up];
  52. }
  53. public boolean full() {
  54. if (up == s.length-1) {
  55. int[] t = new int[s.length*2];
  56. int i;
  57. for (i = 0; i < s.length; i++) {
  58. t[i] = s[i];
  59. }
  60. s = t;
  61. }
  62. return false;
  63. }
  64. public boolean empty() {
  65. return up == -1;
  66. }
  67. }
  68. package listStack;
  69.  
  70. import java.util.Random;
  71.  
  72. public class Stack implements intStack.Stack {
  73. private int[] s;
  74. private int up;
  75. public Stack(int size) {
  76. s = new int[size];
  77. up = -1;
  78. for (int i = 0; i < size; i++) {
  79. pushRandom();
  80. }
  81. }
  82. public void pushRandom() {
  83. Random obj = new Random();
  84. push(obj.nextInt() % 100);
  85. }
  86. public void push(int v) {
  87. s[++up] = v;
  88. }
  89. public int pop() {
  90. return s[up--];
  91. }
  92. public int top() {
  93. return s[up];
  94. }
  95. public boolean full() {
  96. return up == s.length-1;
  97. }
  98. public boolean empty() {
  99. return up == -1;
  100. }
  101. }
  102. package test;
  103.  
  104. import intStack.Stack;
  105.  
  106. public class TestInkStack {
  107. public static void main(String[] args) {
  108. Stack[] stk = new Stack[3];
  109. stk[0] = new fixedStack.Stack(5);
  110. stk[1] = new dynStack.Stack(5);
  111. stk[2] = new listStack.Stack(5);
  112. int i, j;
  113. for (i = 0; i < 2; i++) {
  114. for (j = 1; j <= 10; j++) {
  115. if (stk[i].full())
  116. break;
  117. stk[i].push(j);
  118. }
  119. }
  120. for (i = 0; i < 3; i++) {
  121. while (!stk[i].empty())
  122. System.out.print(stk[i].pop()+ " ");
  123. System.out.println();
  124. }
  125. }
  126. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement