Помогите пожалуйста с кодом. Правильный вывод находится в методе test7(), но мой стек немного не правильно работает. Как правильно переписать код?
Код + тест программы прилагаю ниже. Буду всем благодарен за помощь!!
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StackImpl implements Stack {
Object array[] = new Object[0];
int top = -1;
@Override
public void push(Object element) {
Object[] arrPush = new Object[array.length+1];
for (int i = 0; i < arrPush.length; i++) {
if (i == arrPush.length-1) {
arrPush[i] = element;
} else {
arrPush[i] = array[i];
}
}
array = new Object[arrPush.length];
for (int i = 0; i < array.length; i++) {
array[i] = arrPush[i];
}
top++;
}
@Override
public Object pop() {
Object element = array[size()-1];
if (top == -1) {
throw new NoSuchElementException();
}
Object[] arrRemove = new Object[array.length-1];
for (int i = 0, j = 0; i < array.length; i++, j++) {
if (i == top) {
continue;
} else {
arrRemove[i] = array[i];
}
}
array = new Object[arrRemove.length];
for (int i = 0; i < array.length; i++) {
array[i] = arrRemove[i];
}
top--;
return element;
}
@Override
public Object top() {
return null;
}
@Override
public void clear() {
array = new Object[0];
}
@Override
public int size() {
return array.length;
}
@Override
public Iterator<Object> iterator() {
return new IteratorImpl();
}
class IteratorImpl implements Iterator<Object> {
int current = top;
int currentRem = top;
@Override
public boolean hasNext() {
return current != -1;
}
@Override
public Object next() {
if (current == -1) {
throw new IllegalStateException();
}
int cursor = current;
current = cursor - 1;
return array[cursor];
}
@Override
public void remove() {
top--;
Object arrRem[] = new Object[size()-1];
for (int i = 0, j = 0; i < size(); i++) {
if (i != currentRem) arrRem[j++] = array[i];
}
array = new Object[arrRem.length];
System.arraycopy(arrRem, 0, array, 0, arrRem.length);
currentRem--;
}
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i == array.length - 1) stringBuilder.append(array[i]);
else stringBuilder.append(array[i]).append(", ");
}
return "[" + stringBuilder.toString() + "]";
}
public static void main(String[] args) {
test7();
}
private static void test7() {
Stack stack = new StackImpl();
stack.push("A");
stack.push("B");
stack.push("C");
Iterator it = stack.iterator();
System.out.println(it.next());
System.out.println(it.next());
System.out.println(it.next());
it.remove();
System.out.println(stack);
it = stack.iterator();
System.out.println(it.next());
it.remove();
System.out.println(stack);
it = stack.iterator();
System.out.println(it.next());
it.remove();
System.out.println(stack);
/* an output must be as the following:
*************************************
C
B
A
[B, C]
C
[B]
B
[]
*************************************
*/
}
}