Created
September 11, 2018 08:18
-
-
Save Brutt/b126849713383c9f7b4beefa4d4ca9e9 to your computer and use it in GitHub Desktop.
ArrayStack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArrayStack implements Stack { | |
private Object[] array; | |
private int size; | |
private static final double koeff = 1.5d; | |
public ArrayStack() { | |
int initialCapacity = 2; | |
array = new Object[initialCapacity]; | |
} | |
private boolean isFull(){ | |
return size == array.length; | |
} | |
private void increaseArray(){ | |
Object[] newArray = new Object[(int) (size * koeff)]; | |
System.arraycopy(array, 0, newArray,0, size); | |
array = newArray; | |
} | |
@Override | |
public void push(Object value) { | |
// TODO: check if array is full, create new, and copy values from old one | |
if (isFull()){ | |
increaseArray(); | |
} | |
array[size] = value; | |
size++; | |
} | |
@Override | |
public Object pop() { | |
if(size==0){ | |
return null; | |
} | |
Object result = array[size - 1]; | |
size--; | |
return result; | |
} | |
@Override | |
public Object peek() { | |
if(size==0){ | |
return null; | |
} | |
Object result = array[size - 1]; | |
return result; | |
} | |
@Override | |
public int size() { | |
return size; | |
} | |
@Override | |
public boolean remove(Object value) { | |
boolean result = false; | |
int index = -1; | |
for (int i = 0; i < size; i++) { | |
if(array[i].equals(value)){ | |
index = i; | |
break; | |
} | |
} | |
if(index != -1){ | |
Object[] newArray = new Object[size-1]; | |
System.arraycopy(array, 0, newArray,0, index); | |
System.arraycopy(array, index+1, newArray, index, size - index - 1); | |
array = newArray; | |
size --; | |
result = true; | |
} | |
return result; | |
} | |
@Override | |
public boolean contains(Object value) { | |
boolean result = false; | |
for (Object o : array) { | |
if(o.equals(value)){ | |
result = true; | |
break; | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment