Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using only emptyCheck, top, push, and pop operations, write a function that retu

ID: 3740789 • Letter: U

Question

Using only emptyCheck, top, push, and pop operations, write a function that returns the middle value from a stack S, where the middle of a stack of size n is the INT((n+1)/2)th element. You may create additional stacks as needed. Using only emptyCheck, top, push, and pop operations, write a function that returns the middle value from a stack S, where the middle of a stack of size n is the INT((n+1)/2)th element. You may create additional stacks as needed. Using only emptyCheck, top, push, and pop operations, write a function that returns the middle value from a stack S, where the middle of a stack of size n is the INT((n+1)/2)th element. You may create additional stacks as needed.

Explanation / Answer

public int returnMiddleElement(Stack s){
//s is original stack
int size = s.size();//tells size of original stack
Stack copyStack = new Stack();//used to support our work
int index = 0;//tracks index of original stack
while(!s.isEmpty() && index<(size+1)/2){
//loop till we reach stack is empty or middle index found
copyStack.push(s.pop());//pop from original and push the same to copy stack
}
int resultMiddleElement = s.top();// take the middle element.
while(!copyStack.isEmpty()){
//because of our task, we changed original stack s. now we will get s to previous state
// we will push all elements of copyStack
s.push(copyStack.pop());
}
return resultMiddleElement;// return middle element.
}

Thanks

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote