题目描述
思路,把单链表转化为ArrayList,然后比较前后两个数是否相等。
class Solution {public boolean isPalindrome(ListNode head) {if (head == null) {return false;}List<Integer> valList = new ArrayList<Integer>();ListNode tmp = head;while (tmp != null) { valList.add(tmp.val); //把单链表节点的数值,存储到ArrayList中,方便比较。tmp = tmp.next;}/*** 1. 只比较一半:(valList.size() - 1) / 2* 2. 小于等于*/for (int i = 0; i <= (valList.size() - 1) / 2; i++) { //注意这里的小于等于if (valList.get(i) != valList.get(valList.size() - 1 - i)) {return false;}}return true;}}
如果用双指针的写法,代码如下:
public boolean isPalindromeWithDoublePoint(ListNode head) {if (head == null) {return false;}List<Integer> valList = new ArrayList<Integer>();ListNode tmp = head;while (tmp != null) {valList.add(tmp.val); //把单链表节点的数值,存储到ArrayList中,方便比较。tmp = tmp.next;}int front = 0;int back = valList.size() - 1;while (front < back) {if (valList.get(front) != valList.get(back)) {return false;}back--;front++;}return true;}