234. Palindrome Linked List
Easy
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
package leetcode.easy; public class PalindromeLinkedList { public boolean isPalindrome(ListNode head) { if (head == null) { return true; } java.util.List<Integer> list = new java.util.ArrayList<>(); while (head != null) { list.add(head.val); head = head.next; } int end = list.size() - 1; for (int i = 0; i < end; i++, end--) { if (!list.get(i).equals(list.get(end))) { return false; } } return true; } @org.junit.Test public void test1() { ListNode ln1 = new ListNode(1); ListNode ln2 = new ListNode(2); ln1.next = ln2; ln2.next = null; System.out.println(isPalindrome(ln1)); } @org.junit.Test public void test2() { ListNode ln1 = new ListNode(1); ListNode ln2 = new ListNode(2); ListNode ln3 = new ListNode(2); ListNode ln4 = new ListNode(1); ln1.next = ln2; ln2.next = ln3; ln3.next = ln4; ln4.next = null; System.out.println(isPalindrome(ln1)); } }