Skip to content

Instantly share code, notes, and snippets.

@chouclee
Created June 23, 2014 09:05
Show Gist options
  • Save chouclee/59bd0023cd6c404cfb55 to your computer and use it in GitHub Desktop.
Save chouclee/59bd0023cd6c404cfb55 to your computer and use it in GitHub Desktop.
[CC150][2.7] Implement a function to check if a linked list is a palindrome.
import java.util.LinkedList; //LinkedList in Java is double-linked list
import java.util.ListIterator;
import java.util.Stack;
public class solution {
public static<T> boolean isPalindrome(LinkedList<T> list) {
if (list == null) throw new IllegalArgumentException();
Stack<T> reverse = new Stack<T>();
int N = 0;
for (T element : list) {
reverse.add(element);
N++;
}
ListIterator<T> iter = list.listIterator();
for (int i = 0; i < N/2; i++) {
if (!iter.next().equals(reverse.pop()))
return false;
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<Integer> test = new LinkedList<Integer>();
test.add(1);
System.out.println(test);
if (solution.isPalindrome(test))
System.out.println("Yes");
else System.out.println("No");
test.add(2);
System.out.println(test);
if (solution.isPalindrome(test))
System.out.println("Yes");
else System.out.println("No");
test.add(2);
System.out.println(test);
if (solution.isPalindrome(test))
System.out.println("Yes");
else System.out.println("No");
test.add(1);
System.out.println(test);
if (solution.isPalindrome(test))
System.out.println("Yes");
else System.out.println("No");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment