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
2010-06-08 21:55:38
OP is asking about how to write a Stack class from scratch, not how to use an existing class as a stack.
BoltClock
2010-06-08 21:56:43
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
2010-06-08 21:56:47
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
2010-06-08 21:58:46
Indeed, if it's not marked as homework, then this is the correct answer - he shouldn't be reinventing the wheel.
nojo
2010-06-08 22:01:54
@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
2010-06-08 22:05:51
sorry guys, I have to start from scratch. I forgot to tag it with homework
Mike23
2010-06-09 07:05:18
+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"):
- Find the halfway point
n
of the string (String.length()/2
, or3
in this case) - Iterate over the string. Push the first
n
letters onto the stack in order (r
,a
,c
) - If the length was odd, iterate over the middle letter (
e
) but don't do anything with it - 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
) - 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
2010-06-08 22:01:59