-
-
Save startupjing/1f3b016aa1cc20187ec8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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