Monday, August 12, 2013

Coding Exercises Day 10 (Problem #14)

Problem:
Implement a function to check if a linked list is a palindrome

 boolean isPalindrome(List<T> list) {
  Stack<T> stack = new Stack<T>();

  int size = list.size();

  if (size < 2) return true;
  
  boolean sizeIsOdd = (size % 2 != 0) ? true : false;

  for (int i = 0; i < size; i++) {
    T element = list.get(i);
    
    if (i < size / 2) stack.push(element);
    
    // Ignore the middle element if the list size is odd.
    if ((!sizeIsOdd && i == size / 2) || i > size / 2) {
      if (stack.peek() == element) { 
        stack.pop();
      }
      else {
        return false;
      }
    }
  }
  return true;
}

No comments:

Post a Comment