can't see where it went wrong..
Hi, I'm writing a method that checks a palindrome in a stack.
At the moment it returns true even when the values are not equal.
I would appreciate some help, as I didn't locate the problem.
Code:
public static boolean PalindromeWithStack (Stack s, int numOfElements){
int counter = 0,first,second;
Stack s2=new Stack ();
if (numOfElements ==0) return true; if (numOfElements ==1) return false;
while (counter<numOfElements/2){
s2.push(s.pop());
counter++;
} //devide the stacks evenly.
if (numOfElements %2 != 0) //if odd number of elements
s.pop();
while (counter > 0){
first = s.pop(); second = s2.pop();
if (first!=second){ //after condition
return false; //ends here
}
counter--;
}
return true;
}
}
Thank you.
Yeah something doesn't make sense..
In the tester I'm inserting these lines:
Stack s1 = new Stack();
s1.push(1);
s1.push(3);
and then pass it to the method as: (s1,2). The first is the stack and the second is the number of elements..