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?
代码
Approach #1 Copy into ArrayList and then Use Two Pointer Technique
Complexity Analysis
Time complexity : O(n)
Space complexity : O(n)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */classSolution {publicbooleanisPalindrome(ListNode head) {List<Integer> vals =newArrayList<>();ListNode currentNode = head;while (currentNode !=null) {vals.add(currentNode.val); currentNode =currentNode.next; }int front =0;int back =vals.size() -1;while (front < back) {if (!vals.get(front).equals(vals.get(back))) {returnfalse; } front++; back--; }returntrue; }}