Write a method named changeStack that takes in a Stack of Integer objects named stackIn as a parameter and returns another Stack of Integer objects. The returned Stack contains contents that is the result of switching the top half and the bottom half of the stackIn. But the ordering of integers in each half is NOT changed. In the case of odd-size stackIn, the middle element remains in the same position before and after the switch.
This method is OUTSIDE the class <E>.
Example 1:
stackIn Returned Stack
top top
30 100
10 50
100 30
bottom 50 10 bottom
Example 2:
stackIn Returned Stack
top top
15 65
3 8
200 200
65 15
bottom 8 3 bottom
The Stack class includes all methods necessary for the stack operations. You can consider Stack is like the ArrayDeque in Java API used as a Stack.
public static Stack<Integer> changeStack(Stack<Integer> stackIn)
public static Stack<Integer> changeStack(Stack<Integer> stackIn)
{
//checks if the size of stack is odd or even
if(stackIn.size()%2==0)
{
//finds the half length of the stack
int l=stackIn.size()/2;
//creats two arrays to hold both half of stack
int arr[]=new int[l];
int arr2[]=new int[l];
//pop half stack and store in array
for (int i = 0; i < l; i++) {
arr[i]=stackIn.pop();
}
//pop second half stack and store in array
for (int i=0;i<l;i++) {
arr2[i]=stackIn.pop();
}
//push the first array elements back into the stack one by one in the reverse order
for (int i = l-1; i>=0; i--) {
stackIn.push(arr[i]);
}
//push the second array elements back into the stack one by one in the reverse order
for (int i = l-1; i>=0; i--) {
stackIn.push(arr2[i]);
}
}
else
{
int l=stackIn.size()/2;
int arr[]=new int[l];
int arr2[]=new int[l];
for (int i = 0; i < l; i++) {
arr[i]=stackIn.pop();
}
//size of the stack is odd so the next element after popping half the array
//must be the middle element. Store it separately in an integer variable
int middleElement=stackIn.pop();
for (int i=0;i<l;i++) {
arr2[i]=stackIn.pop();
}
for (int i = l-1; i>=0; i--) {
stackIn.push(arr[i]);
}
//after storing the half elements back in the array, we mush push the middle element
//as its position should remain unchanged
stackIn.push(middleElement);
for (int i = l-1; i>=0; i--) {
stackIn.push(arr2[i]);
}
}
return stackIn;
}
Refer to the screenshot below for better clarity and indentation:
Get Answers For Free
Most questions answered within 1 hours.