Cj Bunn
Cj Bunn

Reputation: 3

Duplicating elements in a stack?

So I have a method to take a stack of Integers, and return the stack with all of the elements duplicated, and in the same order. My problem is with the method i currently have, Im getting an infinite loop problem on all cases except when the Stack is empty. What can i do to complete the duplication without a looping problem?

public void stutter(Stack<Integer> Integ)
{
    Integer first;

    for(int i = 0; i < Integ.size(); i++)
    {
         first = Integ.pop();
         Integ.push(first);
        Integ.push(first);
    }
}

Upvotes: 0

Views: 256

Answers (3)

Denis gruzdev
Denis gruzdev

Reputation: 1

Just create new stack with duplicates (and replace old if needed).

Upvotes: 0

Paulo Ara&#250;jo
Paulo Ara&#250;jo

Reputation: 569

Each time you push another integer, you increase the original size of your stack, pushing your "i" limit forward.

You should return a new Stack, preferably using (pre java8):

public Stack<Integer> stutter(Stack<Integer> from) {
    Stack<Integer> stk = new Stack<>();
    for(Integer i: from) {
        stk.push(i);
        stk.push(i);
    }
    return stk;
}

Upvotes: 1

Manu
Manu

Reputation: 182

ofc, its an inifinite loop. You increase the Integ.size() inside of the loop by Integ.push().

Try something like that. Save the size inside a var befor starting to push new elements into it.

int size = Integ.size();
for(int i = 0; i < size; i++){
   first = Integ.pop();
   Integ.push(first);
   Integ.push(first);
}

Upvotes: 0

Related Questions