Reputation: 1471
I'm supposed to feed an Arraylist into a stack, and then obviously build a list from that stack. Theoretically this means that the list should be reversed, yes? I thought I had it all in the bag, but my output is thusly:
[1, 2, 3, 4, 5]
AAAAANNNDDDDD REVERSE!
[1, 2, 3, 4, 5]
So obviously I goofed somewhere, but I can't tell where. Code follows, but be warned, I'm not horribly good at this, so if there's something that horribly offends you, but isn't actually the problem, I'd prefer it not be the focus of discussion.
package stackclass;
import java.util.ArrayList;
import java.util.Stack;
public class StackClass
{
static ArrayList<String> list = new ArrayList();
static Stack<String> popper = new Stack();
public static ArrayList<String> reverse(ArrayList<String> n)
{
for(int i = 0; i != n.size();)
{
popper.push(n.get(n.size() - 1));
n.remove(n.size() - 1);
}
for(int i = 0; i != popper.size();)
{
n.add(popper.pop());
}
return n;
}
public static void main(String[] args)
{
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
System.out.println(list);
System.out.println("AAAAANNNDDDDD REVERSE!");
ArrayList n = reverse(list);
System.out.println(n);
}
}
Any and all help is appreciated.
Upvotes: 0
Views: 661
Reputation: 17422
In your first for-loop, you should take the first element rather than the last one from the list:
public static ArrayList<String> reverse(ArrayList<String> n)
{
for(int i = 0; i < n.size(); i++)
{
popper.push(n.get(i));
n.remove(0);
}
for(int i = 0; i != popper.size(); i++)
{
n.add(popper.pop());
}
return n;
}
you're also missing to increment your counters (i++)
Upvotes: 1
Reputation: 5912
public static ArrayList<String> reverse(ArrayList<String> n)
{
while(!n.isEmpty())
{
popper.push(n.get(0));
n.remove(0);
}
while(!popper.isEmpty()){
n.add(popper.pop());
}
return n;
}
This works.
Upvotes: 1