How to reverse the elements of stack using only stack operations for example: 2)
ID: 3731617 • Letter: H
Question
How to reverse the elements of stack using only stack operations for example: 2) For our MyStack class we created methods emptyCheck() which returns True if the stack becomes empty; top), that returns the value of the top element in the stack; push(a1) that places the value of al onto the top of the stack; and popi) that removes the top element of the stack, if any. To process any stack, you may only use those routines and some primitive data variables to temporarily store a value or two. If necessary, you can temporarily create a second stack to store values. a) Design a method in MyStack called getBottomValue() that returns the values at the bottom of the stack. Design a method in MyStack called stackStack(MyStack that pushes the values from stack T, in the correct order. When the routine is done, the top element in the ("this") stack should be the top element from T. T should also be restored to its original condition. b) Illustration Stack T 6 The ('this") Stack Resulting "this" StackExplanation / Answer
Answer of a-
// suppose MyStack class contain thisStack stack
//stack<int> thisStack;
int getBottomValue(){
stack<int> tempStack; // this is temp stack
while(!thisStack.empty()){
tempStack.push(st.top()); // push the element of thisStack stack to tempStack
thisStack.pop();
}
int val = tempStack.top();
// now again empty the tempStack and fill the thisStack
while(!tempStack.empty()){
st.push(tempStack.top());
tempStack.pop();
}
return val; //return the bottom value of thisStack
}
Answer b-
void stackStack(stack<int> &Te){
// pop the Te stack and push in to tempStack
while(!Te.empty()){
tempStack.push(Te.top());
Te.pop();
}
while(!tempStack.empty()){
//pop the tempStack and push into thisStack
thisStack.push(tempStack.top());
tempStack.pop();
}
//this will print the final thisStack with containing T stack element in sequence and top of the element of thisStack
// is same as top of the element of T stack
while(!thisStack.empty()){
cout<<thisStack.top();
tempStack.pop();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.