- Java and JSP
||10-01-2012 09:58 PM
Palindrome using stack,queue
Need some help with a little coding problem.
I need to check if it is a Palindrome using a queue and a stack, by implementing a method that tests whether a sequence of numbers is a palindrome, that is, equal to the sequence in reverse.
the code in [...] is My Code, while everything else is unchangeable any help is appreciated.
public class QueueStackUtil
public static boolean isPalindrome(int values)
Queue<Integer> queue = new LinkedList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
for (int s : values)
// insert s into the queue and stack
//ins in queue
while (queue.size() > 0)
[MyCode// remove an element from the queue
for(int i=0; i<tail;i++)
queue[i] = queue[i+1];
// remove an element from the stack
// compare the removed elements
||10-01-2012 11:31 PM
Making use of both a queue and a stack, this is the shortest I could come up with:
public class Palindrome
private Deque<Character> stack = new LinkedList<Character>();
private Deque<Character> queue = new LinkedList<Character>();
private String s;
public Palindrome(String s)
this.s = s;
for (Character c : s.toCharArray())
c = Character.toLowerCase(c);
public boolean isPalindrome()
public String getString()
public static void main(String argv)
Palindrome p = new Palindrome("Madam I'm Adam");
System.out.println("'" + p.getString() + "' is" + (p.isPalindrome() ? "" : " not") + " a palendrome");
Realistically, if I were to check for a palindrome I would would grab a string from the middle and compare outside moving both backwards and forwards, and skip over any non letter or digit. That would let me drop the iterative count to 1/2 that of the string length if it is a palindrome.
Since your code is clearly homework, you'll need to do some adaptations here. First, you're stuck using the queue and stack classes (which are not recommended). LinkedList is easy since it implements the Deque, so you can actually treat it as both a stack and a queue.
This makes no sense:
. Values represents the entire int, and s[x] represents an invalid offset to a numerical data. This syntax:
for (int s : values)
is java's equivalent to a foreach. So the 's' here represents a single integer value which you need to push onto the lists. To add items to your stack, use the
method. To add to the queue, use the
Now in the while loop, you simply capture the results of
. If they don't match, you need to return false.
That's a little curious I have to admit, more often than not educational facilities prefer a single point of return and opt for a variable instead of an inline return.
|All times are GMT +1. The time now is 11:48 AM.
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.