题目地址:https://leetcode.cn/problems/palindrome-linked-list/
思路一:遍历两次,第一次依次取出所有节点并存放在数组arr中,第二次,链表向前遍历,数组向后遍历,比较每个元素是否相等,如果都相等则为回文链表。代码如下:
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<Integer>();
ListNode cur = head;
while(cur != null) {
list.add(cur.val);
cur = cur.next;
}
int i = list.size()-1;
while(head != null) {
if(head.val != list.get(i)) {
return false;
}
head = head.next;
i--;
}
return true;
}
}