Stuck with stacks

• 01-30-2011, 04:57 PM
Yakg
Stuck with stacks
Hello everyone I'm trying to write a palindrome stack method that will check numbers. Something went wrong with an never ending loop. As for any comments on the method like complexity and more I would be glad to hear.

I'm very new to the stack subject so hope it's more or less all right.

Code:

```public static boolean PalindromeStack (Stack s, int num){ int counter = 0; Stack s2 = new Stack (); while (counter < num/2){ s2.push(s.pop()); counter++;} s.pop(); while (s !=null) if (s.equals (s2)){ return false;} else s.pop(); s2.pop(); return true;       }     }```

Thanks.
• 01-30-2011, 05:06 PM
JosAH
Quote:

Originally Posted by Yakg
Hello everyone I'm trying to write a palindrome stack method that will check numbers. Something went wrong with an never ending loop. As for any comments on the method like complexity and more I would be glad to hear.

I'm very new to the stack subject so hope it's more or less all right.

Code:

```public static boolean PalindromeStack (Stack s, int num){ int counter = 0; Stack s2 = new Stack (); while (counter < num/2){ s2.push(s.pop()); counter++;} s.pop(); while (s !=null) if (s.equals (s2)){ return false;} else s.pop(); s2.pop(); return true;       }     }```

You're testing s != null in your second loop; s will never equal null, it may become empty but that's all.

kind regards,

Jos
• 01-30-2011, 09:34 PM
Yakg
I re wrote it but still
now I have a problem comparing the values inside the stacks, for some reason I'm getting true even though the values are different.
why is that? isEqual and isEmpty methods are not allowed for me to use.

Here's the code:

Code:

```public static boolean PalindromeWithStack (Stack s, int numOfElements){ int counter = 0; int 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++;} //devided stacks. if (numOfElements %2 != 0) s.pop(); //if odd or even. while (counter > 0){ first = s.pop(); second = s2.pop(); if (first != second)        //after condition return false;      //ends here counter--;      } return true;     }     }```
Thanks