Advertisement
Guest User

checkpalindromequeue

a guest
Dec 8th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. class Solution {
  2.   /**
  3.    * Checks for a String represented as a SLList whether this String is a palindrome.
  4.    * This is done by using a queue.
  5.    *
  6.    * An empty String or null should return true.
  7.    *
  8.    * @param list
  9.    *     SLList used to represent a String
  10.    * @return true if the String represented as a SLList is a palindrome, otherwise false
  11.    */
  12.   public static boolean checkPalindrome(SLList list) {
  13.     if (list == null || list.size() < 1) {
  14.       return true;
  15.     }
  16.         LibraryQueue<Entry> queue = new LibraryQueue<>();
  17.         if (list.size() % 2 == 0) {
  18.           int half = list.size() / 2;
  19.  
  20.           for (int i = 0; i < half; i++) {
  21.                 char c = list.removeFirst();
  22.                 Entry e = new Entry(i, c);
  23.                 queue.enqueue(e);
  24.             }
  25.  
  26.             for (int i = 0; i < half; i++) {
  27.                 if (queue.dequeue().getElement() != list.removeFirst()) {
  28.                     return false;
  29.                 }
  30.             }
  31.         }
  32.         else {
  33.             int half = (list.size() - 1) / 2;
  34.  
  35.             for (int i = 0; i < half; i++) {
  36.                 char c = list.removeFirst();
  37.                 Entry e = new Entry(i, c);
  38.                 queue.enqueue(e);
  39.             }
  40.             list.removeFirst();
  41.  
  42.             for (int i = 0; i < half; i++) {
  43.                 if (queue.dequeue().getElement() != list.removeFirst()) {
  44.                 return false;
  45.                 }
  46.             }
  47.         }
  48.     return true;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement