Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Stack;
- public class Palindrome {
- /**
- * Determine if a linked list is a palindrome
- * @param List<Character>
- * @return boolean
- */
- public static boolean isPalindrome(List<Character> list) {
- Stack<Character> letters = new Stack<>();
- // Push the first half of the list onto a stack
- int i = 0;
- for(; i < list.size() / 2; i++) {
- letters.push(list.get(i));
- }
- // if the list is of odd size skip the center letter
- if(list.size() % 2 != 0) {
- i++;
- }
- // verify the end of the list is the opposite of the beginning
- for(; i < list.size(); i++) {
- if(letters.pop() != list.get(i)) {
- return false;
- }
- }
- return true;
- }
- public static void main(String[] args) {
- for(int i = 0; i < args.length; i++) {
- List<Character> palindrome = new LinkedList<>();
- for(int j = 0; j < args[i].length(); j++) {
- palindrome.add(args[i].charAt(j));
- }
- System.out.println("Is " + args[i] + " a palindrome?:\t" + Palindrome.isPalindrome(palindrome));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement