public class ArrayStackImpl<AnyType> implements Stack<AnyType>
{
// large array limit to store the stack
public final int LIMIT = 10000000;
// the actual storage with a pointer to the top of the stack
private AnyType[] vals = (AnyType[]) new Object[LIMIT];
private int topPointer = -1;
// return the top of the stack by pointing to top point
public AnyType top()
{
return vals[topPointer];
}
// return the top and reduce the top pointer
public AnyType pop()
{
AnyType tmp = top();
topPointer--;
return tmp;
}
// increase the top pointer and add the data
public void push(AnyType data)
{
topPointer++;
vals[topPointer] = data;
}
// returns true if the stack is empty
public boolean empty()
{
return topPointer == -1;
}
}
public void stackArrange(ArrayList list1, ArrayList list2)
{
ArrayStackImpl<Integer> s = new ArrayStackImpl<Integer>();
if (list1.isEmpty()) {
throw new IllegalArgumentException("Array is Empty");
}
if (s.empty()) {
s.push((Integer) list1.get(list1.size() - 1));
}
for (int i = list1.size() - 2; i >= 0; i--) {
int e = (Integer) list1.get(i);
if (e >= s.top()) {
while (!s.empty()) {
list2.add(s.pop());
}
s.push(e);
}
else {
s.push(e);
}
}
}
I having a problem in the popping of element. I need to compare the element in the stack if element is greater than then, pop the element in the stack and push in the current one. so for example, stay from the back of this arraylist 1, 4, 3, 2, 7, 3, 6, 4 If stack is empty, push 4 into the stack 6 is greater than 4 so pop 4 and push 6 into the stack. 3 is smaller than push 3 into the stack. 7 is greater than 3 so pop 3 and pop 6 using while loop.
here come the problem when i debug it. the 7 overwrite the 6 in the stack even thought the top pointer is -1.
What is my mistake in the while loop?