请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
lc练习
public boolean isPalindrome(ListNode head) { if (head == null) { return true; } List<Integer> list = new ArrayList<>(); ListNode node = head; while (node != null) { list.add(node.val); node = node.next; } int start = 0; int end = list.size() - 1; while (start < end) { if (!list.get(start).equals(list.get(end))) { return false; } start++; end--; } return true; }
private ListNode frontPointer; private boolean recursivelyCheck(ListNode currentNode) { if (currentNode != null) { if (!recursivelyCheck(currentNode.next)) { return false; } if (currentNode.val != frontPointer.val) { return false; } frontPointer = frontPointer.next; } return true; } public boolean isPalindrome(ListNode head) { frontPointer = head; return recursivelyCheck(head); } // https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/