Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- /**
- *
- * @author bdb52
- */
- public class StackSort<T extends Comparable<? super T>> {
- private VectorStack<T> store, temp;
- private int size;
- public StackSort() {
- store = new VectorStack<>();
- temp = new VectorStack<>();
- int size = 0;
- }
- public boolean add(T obj) {
- if (obj == null)
- return false;
- findStackLocation(obj);
- store.push(obj);
- size++;
- emptyTempStack();
- return true;
- }
- public int size () {
- return size;
- }
- public boolean contains(T obj) {
- if (obj == null)
- return false;
- boolean found = false;
- findStackLocation(obj);
- while (!found && !store.empty() && store.peek().compareTo(obj) == 0) {
- if (store.peek().equals(obj))
- found = true;
- else
- temp.push(store.pop());
- emptyTempStack();
- }
- return found;
- }
- public boolean remove(T obj) {
- if (obj == null)
- return false;
- boolean found = false;
- findStackLocation(obj);
- store.pop();
- size--;
- found = true;
- emptyTempStack();
- return found;
- }
- public Object [] toArray() {
- Object[] arr = new Object[size];
- for (int x = 0; x < size; x++) {
- arr[x] = store.pop();
- temp.push((T)arr[x]);
- }
- emptyTempStack();
- return arr;
- }
- public Object [] reverseToArray() {
- Object[] revarr = new Object[size];
- for (int i = size; i > 0; i--) {
- temp.push(store.pop());
- }
- for (int j = 0; j < size; j++) {
- revarr[j] = temp.pop();
- store.push((T)revarr[j]);
- }
- return revarr;
- }
- private void findStackLocation(T obj) {
- while(!store.empty() && store.peek().compareTo(obj) < 0) {
- temp.push(store.pop());
- }
- }
- private void emptyTempStack() {
- while (!temp.empty()) {
- store.push(temp.pop());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement