Skip to content

Instantly share code, notes, and snippets.

@startupjing
Created July 2, 2014 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupjing/1f3b016aa1cc20187ec8 to your computer and use it in GitHub Desktop.
Save startupjing/1f3b016aa1cc20187ec8 to your computer and use it in GitHub Desktop.
import java.util.*;
public class CheckPalindrome {
public static void main(String[] args) {
MyList<Integer> l1 = new MyList<Integer>(new Integer[] {1,2,3,4,3,2,1});
MyList<Integer> l2 = new MyList<Integer>(new Integer[] {1,2,2});
l1.print();
System.out.println("Is list palindrome: " + isPalindrome(l1));
System.out.println();
l2.print();
System.out.println("Is list palindrome: " + isPalindrome(l2));
}
/**
* use a stack to check palindrome
* @param list
* @return true if list is palindrome
*/
public static boolean isPalindrome(MyList<Integer> list){
Stack<Integer> s = new Stack<Integer>();
Node<Integer> curr = list.head;
//store value into stack
while(curr != null){
s.push(curr.val);
curr = curr.next;
}
//pop from stack and compare to the list
curr = list.head;
while(!s.isEmpty()){
if(s.pop() != curr.val){
return false;
}
curr = curr.next;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment