Kotlinlearncs.online LogoJava
Return to List

Solve: Insert into Stack

Created By: Justin Maier
/ Version: 2024.12.1

Complete the method insertIntoStack that inserts a given value into a stack at a particular index. It will take three parameters:

  • A Stack<Integer>.
  • A value to be inserted into the stack.
  • The index where the value should be inserted into the stack. Consider the stack to be indexed starting from the bottom element as index 0.

If the passed stack argument is null, throw an IllegalArgumentException.

If the index argument is out of bounds, throw an IndexOutOfBoundsException.

Hint 1: you can use the .size() method to get the number of elements in a stack.

Hint 2: create a second stack.

void insertIntoStack(Stack<Integer> stack, int value, int index) {
return; // You may need to remove this starter code
}

Related Lessons

Stuck? You may find these lessons helpful: