方法1:数组+双指针
时间复杂度:$O(n)$
空间复杂度:$O(1)$
解题思路
见注释。
Java 代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<>();
//把链表元素的值复制到数组里
ListNode cur = head;
while (cur != null) {
vals.add(cur.val);
cur = cur.next;
}
int l = 0, r = vals.size() - 1;
while (l < r) {
if (!vals.get(l).equals(vals.get(r))) {
return false;
}
l ++;
r --;
}
return true;
}
}