I am trying to create a method so that I can be able to insert a node at position n in my custom designed stack (built on an Array). When I use stack.pop()
as a parameter in stack.push()
I get ArrayIndexOutOfBoundsException: -1
.
I have tried to replace stack.pop(stack.push())
with a variable representing it, and I got the same exception (ArrayIndexOutOfBoundsException: -1
).
Stack class
public class Stack {
public Node[] stackList = new Node[12];
int index = 0; //Sets index to 0
public void push(Node node){ //Adds nodes to the top of the stack.
stackList[index] = node;
if (index < (stackList.length - 1)){
index++;
}
}
public Node pop(){ //Removes node from stack.
Node output = stackList[index];
stackList[index] = null;
index--;
return output;
}
public void printStack(){
for (int j = 0; j < stackList.length; j++){
stackList[j].printValue();
}
}
public int size(){
return stackList.length;
}
public void insertNode(int val, int pos, Stack stack){
Stack tmpstack = new Stack();
Node value = new Node();
value.changeValue((val));
int i=0; //Sets index to 0
while(i<pos){
tmpstack.push(stack.pop());
i++;
}
stack.push(value);
while(tmpstack.size() > 0)
stack.push(tmpstack.pop());
}
Method in main-class
public class Main {
public static void main(String[] args){
//Stack
System.out.println("Starting to print the value of the stack:");
Stack s = new Stack();
for (int i = 0; i < 12; i++) {
Node node = new Node();
node.changeValue((i+1));
s.push(node);
}
s.printStack();
s.insertNode(77,5, s); //value, position, stack
s.printStack();