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

Question 2.6 RemoveFirst (second method) The second method removeFirst is a clas

ID: 3707926 • Letter: Q

Question

Question 2.6 RemoveFirst (second method) The second method removeFirst is a class method of StacksAndQueues that takes two input parameters: a Stack of String instances and a String instance. After calling that method, the first occurrence of that string has been removed from the stack. If that string was not in the stack, then the stack is left unchanged For example, if the following stack is passed to removeFirst top)->[a, b, c, a, b, c, a, b, c(bottom) and the second parameter is the string "a", after the call, the stack should contain (top) -> [b, c, a, b, c, a, b, cl [a, c, a, b, c, a, b, c ]

Explanation / Answer

import java.util.ArrayDeque; import java.util.Queue; import java.util.Stack; public class StacksAndQueues { public void reverseQueue(Queue queue) { if(queue.isEmpty()) { return; } Stack tmp = new Stack(); while (!queue.isEmpty()) { tmp.push(queue.poll()); } while (!tmp.empty()) { queue.add(tmp.pop()); } } void removeAll(Queue queue, String toRemove) { if(queue == null || queue.isEmpty()) { return; } Queue tmp = new ArrayDeque(); while (!queue.isEmpty()) { String str = queue.poll(); if(!str.equals(toRemove)) { tmp.add(str); } } while(!tmp.isEmpty()) { queue.add(tmp.poll()); } } void removeAll(Stack stack, String toRemove) { if(stack == null || stack.isEmpty()) { return; } Stack tmp = new Stack(); while (!stack.isEmpty()) { String str = stack.pop(); if(!str.equals(toRemove)) { tmp.push(str); } } while(!tmp.isEmpty()) { stack.push(tmp.pop()); } } void removeFirst(Queue queue, String toRemove) { if(queue == null || queue.isEmpty()) { return; } Queue tmp = new ArrayDeque(); boolean alreadyRemoved = false; while (!queue.isEmpty()) { String str = queue.poll(); if(alreadyRemoved || !str.equals(toRemove)) { tmp.add(str); } else { alreadyRemoved = true; } } while(!tmp.isEmpty()) { queue.add(tmp.poll()); } } void removeFirst(Stack stack, String toRemove) { if(stack == null || stack.isEmpty()) { return; } Stack tmp = new Stack(); boolean alreadyRemoved = false; while (!stack.isEmpty()) { String str = stack.pop(); if(alreadyRemoved || !str.equals(toRemove)) { tmp.push(str); } else { alreadyRemoved = true; } } while(!tmp.isEmpty()) { stack.push(tmp.pop()); } } }
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