what can I use insted of .get? .get() is not part of the class, so I am having t
ID: 3746052 • Letter: W
Question
what can I use insted of .get? .get() is not part of the class, so I am having trouble. my solution is below
/*
* reverseAStack
* returns a new stack containing the contents of s reversed
* precondition: input stack s maybe empty
* postcondition:
* return a new stack with contents reversed
* original stack is unchanged
* you may use: basic java arrays; Stack<>, Queue<> from algs13
* you may not use any other Java classes, algorithms without permission
* your solution must be all client code: you may not alter the original Stack, Queue classes
*/
public static Stack<String> reverseAStack(Stack<String> s) {
Stack<String> reverse = new Stack<>();
for(int i = 0;i<s.size();i++){
reverse.push(s.get(i));
}
return reverse;
}
Explanation / Answer
import java.util.ArrayDeque; import java.util.Queue; import java.util.Stack; public class ReverseAStack { /* * reverseAStack * returns a new stack containing the contents of s reversed * precondition: input stack s maybe empty * postcondition: * return a new stack with contents reversed * original stack is unchanged * you may use: basic java arrays; Stack, Queue from algs13 * you may not use any other Java classes, algorithms without permission * your solution must be all client code: you may not alter the original Stack, Queue classes */ public static Stack reverseAStack(Stack s) { Queue queue = new ArrayDeque(); Stack temp = new Stack(); while (!s.empty()) { queue.add(s.peek()); temp.push(s.pop()); } Stack reversedStack = new Stack(); while (!queue.isEmpty()) { reversedStack.push(queue.remove()); s.push(temp.pop()); } return reversedStack; } public static void main(String[] args) { Stack stack = new Stack(); stack.push("first"); stack.push("second"); stack.push("third"); System.out.println("Original stack: " + stack); System.out.println("Reversed stack: " + reverseAStack(stack)); System.out.println("Original stack after calling reverse method: " + stack); } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.