Question

What is wrong with the following code? This piece of code incorrectly attempts to remove all...

  1. What is wrong with the following code? This piece of code incorrectly attempts to remove all even values from a stack integers. How would you fix it? You will need to write a class with the main(String[] args) {….} method to test the following piece of code, find the problem, and fix it.

               while (!s1.isEmpty()){

                              int n = s1.pop();

                              if (n % 2 != 0) {

                                s1.push(n); // if odd put it back.

                              }

               }

0 0
Add a comment Improve this question Transcribed image text
Answer #1
/*
Given code forms an infinite loop, because s1 stack will never be empty if there are odd numbers in the stack
so, use a temporary stack move all odds to a different stack first
and then copy the temporary stack back into the original stack
 */
import java.util.Stack;

public class RemoveStackEvens {

    public static void main(String[] args) {
        Stack<Integer> s1 = new Stack<>();
        s1.push(2);
        s1.push(3);
        s1.push(9);
        s1.push(6);
        s1.push(7);
        s1.push(4);
        s1.push(5);
        System.out.println("Original stack: " + s1);
        Stack<Integer> temp = new Stack<>();
        while (!s1.isEmpty()) {
            int n = s1.pop();
            if (n % 2 != 0) {
                temp.push(n);
            }
        }
        while (!temp.isEmpty()) {
            s1.push(temp.pop());
        }
        System.out.println("Modified stack: " + s1);
    }
}

Add a comment
Know the answer?
Add Answer to:
What is wrong with the following code? This piece of code incorrectly attempts to remove all...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • in c++ please include all of the following " template class, template function, singly linked list,...

    in c++ please include all of the following " template class, template function, singly linked list, the ADT stack, copy constructor, operator overloading, "try catch"and pointers Modify the code named "Stack using a Singly Linked List" to make the ADT Stack that is a template class has the code of the destructor in which each node is directly deleted without using any member function. As each node is deleted, the destructor displays the address of the node that is being...

  • Write a program that uses a stack to reverse its inputs. Your stack must be generic...

    Write a program that uses a stack to reverse its inputs. Your stack must be generic and you must demonstrate that it accepts both String and Integer types. Your stack must implement the following methods: push, pop, isEmpty (returns true if the stack is empty and false otherwise), and size (returns an integer value for the number of items in the stack). You may use either an ArrayList or a LinkedList to implement your stack. Also, your pop method must...

  • Help with c++ program. The following code takes an infix expression and converts it to postfix....

    Help with c++ program. The following code takes an infix expression and converts it to postfix. When I compile the code it returns "Segmentation fault". However I don't know what causes this. #include #include #include using namespace std; template class Stack { public: Stack();//creates the stack bool isempty(); // returns true if the stack is empty T gettop();//returns the front of the list void push(T entry);//add entry to the top of the stack void pop();//remove the top of the stack...

  • I need help with this code This is what I need to do: Implement the Stack...

    I need help with this code This is what I need to do: Implement the Stack Class with an ArrayList instead of an array, including the following functions: • empty • push • peek • pop • overrided toString( ) function which returns all of the stack’s contents Things to note: • You no longer need a size. • You no longer need to define a constant DEFAULT_CAPACITY. Since ArrayLists grow dynamically. • Whenever possible, use ArrayList functions instead of...

  • Implement the following code using ARM instructions. //Objective to practice on procedure, push and pop. int...

    Implement the following code using ARM instructions. //Objective to practice on procedure, push and pop. int a=3,b=6,c=2,d=5; /* use registers to store values in global variables*/ main {           checkEvenfun()            sunFun()        } checkEvenfun() {                             Check if the register have even numbers if odd replace with 0.                             Push values in stack.                            }          sunFun(){                            Pop from stack find the sum }

  • For merge sort the time complexity is Θ(nlogn), but what if we had two unsorted stacks...

    For merge sort the time complexity is Θ(nlogn), but what if we had two unsorted stacks and wanted to but merge them into one final sorted stack! what is the time complexity then? code / Java program to merge to unsorted stacks // into a third stack in sorted way. import java.io.*; import java.util.*;    public class GFG {            // This is the temporary stack     static Stack<Integer> res = new Stack<Integer>();     static Stack<Integer> tmpStack = new Stack<Integer>();            //...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT