tags:

views:

162

answers:

2

How do I write a stack class in Java while checking for palindrome words and phrases?

A: 
LinkedList<String> stack = new LinkedList<String>();

// Push on top of stack
stack.addFirst("abc");

// Pop off top of stack
String str = stack.getFirst();
Dolph
OP is asking about how to write a Stack class from scratch, not how to use an existing class as a stack.
BoltClock
If this is really homework (it's indeed a *typical* homework question), then you're often not allowed to make use of existing API's, but instead you should "reinvent" it :)
BalusC
It wasn't tagged with `homework` when I answered it. Regardless, it's certainly useful to reference the existing API's source code / documentation to learn **how** it's *already* been done.
Dolph
Indeed, if it's not marked as homework, then this is the correct answer - he shouldn't be reinventing the wheel.
nojo
@nojo: Though there then would seem to be an overabundance of people encountering palindromes in their work domains. Myself, I'm lucky if I test for palindromes more than twice a month!
Mark Peters
sorry guys, I have to start from scratch. I forgot to tag it with homework
Mike23
+4  A: 

The question is a little unclear, but I'm guessing you're supposed to use a stack to check if a given word is a palindrome. To do so (examples assume the string "racecar"):

  1. Find the halfway point n of the string (String.length()/2, or 3 in this case)
  2. Iterate over the string. Push the first n letters onto the stack in order (r, a, c)
  3. If the length was odd, iterate over the middle letter (e) but don't do anything with it
  4. Keep iterating, but pop off the stack as you do so, checking that each popped character equals the current character in the string (c, a, r)
  5. If the stack empties as you reach the end of the string, it's a palindrome

If you actually need to implement a stack, that's a whole separate issue, but it seems unlikely a teacher assigned you both at once, so I'm guessing you're just supposed to use an existing stack

Michael Mrozek