Advertisement
Guest User

Untitled

a guest
May 30th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.List;
  3. import java.util.Stack;
  4.  
  5. public class Palindrome {
  6. /**
  7. * Determine if a linked list is a palindrome
  8. * @param List<Character>
  9. * @return boolean
  10. */
  11. public static boolean isPalindrome(List<Character> list) {
  12. Stack<Character> letters = new Stack<>();
  13.  
  14. // Push the first half of the list onto a stack
  15. int i = 0;
  16. for(; i < list.size() / 2; i++) {
  17. letters.push(list.get(i));
  18. }
  19.  
  20. // if the list is of odd size skip the center letter
  21. if(list.size() % 2 != 0) {
  22. i++;
  23. }
  24.  
  25. // verify the end of the list is the opposite of the beginning
  26. for(; i < list.size(); i++) {
  27. if(letters.pop() != list.get(i)) {
  28. return false;
  29. }
  30. }
  31.  
  32. return true;
  33. }
  34.  
  35.  
  36. public static void main(String[] args) {
  37.  
  38. for(int i = 0; i < args.length; i++) {
  39.  
  40. List<Character> palindrome = new LinkedList<>();
  41.  
  42. for(int j = 0; j < args[i].length(); j++) {
  43. palindrome.add(args[i].charAt(j));
  44. }
  45.  
  46. System.out.println("Is " + args[i] + " a palindrome?:\t" + Palindrome.isPalindrome(palindrome));
  47. }
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement