Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1.  
  2. /*
  3. * To change this license header, choose License Headers in Project Properties.
  4. * To change this template file, choose Tools | Templates
  5. * and open the template in the editor.
  6. */
  7.  
  8. /**
  9. *
  10. * @author bdb52
  11. */
  12. public class StackSort<T extends Comparable<? super T>> {
  13. private VectorStack<T> store, temp;
  14. private int size;
  15.  
  16. public StackSort() {
  17. store = new VectorStack<>();
  18. temp = new VectorStack<>();
  19. int size = 0;
  20. }
  21.  
  22. public boolean add(T obj) {
  23. if (obj == null)
  24. return false;
  25. findStackLocation(obj);
  26. store.push(obj);
  27. size++;
  28. emptyTempStack();
  29. return true;
  30. }
  31.  
  32. public int size () {
  33. return size;
  34. }
  35.  
  36. public boolean contains(T obj) {
  37. if (obj == null)
  38. return false;
  39. boolean found = false;
  40.  
  41. findStackLocation(obj);
  42.  
  43. while (!found && !store.empty() && store.peek().compareTo(obj) == 0) {
  44. if (store.peek().equals(obj))
  45. found = true;
  46. else
  47. temp.push(store.pop());
  48.  
  49. emptyTempStack();
  50. }
  51. return found;
  52. }
  53.  
  54. public boolean remove(T obj) {
  55. if (obj == null)
  56. return false;
  57. boolean found = false;
  58.  
  59. findStackLocation(obj);
  60. store.pop();
  61. size--;
  62. found = true;
  63.  
  64. emptyTempStack();
  65. return found;
  66. }
  67.  
  68. public Object [] toArray() {
  69. Object[] arr = new Object[size];
  70. for (int x = 0; x < size; x++) {
  71. arr[x] = store.pop();
  72. temp.push((T)arr[x]);
  73. }
  74. emptyTempStack();
  75. return arr;
  76. }
  77.  
  78. public Object [] reverseToArray() {
  79. Object[] revarr = new Object[size];
  80. for (int i = size; i > 0; i--) {
  81. temp.push(store.pop());
  82. }
  83. for (int j = 0; j < size; j++) {
  84. revarr[j] = temp.pop();
  85. store.push((T)revarr[j]);
  86. }
  87. return revarr;
  88. }
  89.  
  90. private void findStackLocation(T obj) {
  91. while(!store.empty() && store.peek().compareTo(obj) < 0) {
  92. temp.push(store.pop());
  93. }
  94. }
  95.  
  96. private void emptyTempStack() {
  97. while (!temp.empty()) {
  98. store.push(temp.pop());
  99. }
  100. }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement