方法1
回文链表我们可以先找到中间节点:
两种方式:利用双指针,一个每次走1格,一个每次走两格;另一种遍历出链表长度之后,再遍历一遍找到中间节点,然后把中间节点后的链表倒序,就是上一道题的链表反转,最后从节点头和节点尾进行依次判断
判断的时候要注意分情况,因为链表长度可能为奇数也可能为偶数,如果为奇数那么只需要head != reHead跳出循环返回true;但是如果为偶数我们用head.next != reHead跳出循环的时候还需要判断head.val是否等于reHead.val
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
int sum = 0;
ListNode cur = head;
while(cur != null){
sum++;
cur= cur.next;
}
int count = sum / 2;
ListNode minNode = head;
for(int i = 0 ; i < count;i++){
minNode = minNode.next;
}
//反转链表
ListNode reHead = func(minNode);
//进行判断
while(head != reHead && head.next != reHead ){
if(head.val != reHead.val) return false;
head = head.next;
reHead = reHead.next;
}
if(head.next == reHead){
if(head.val != reHead.val) return false;
}
return true;
}
public ListNode func(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode node = func(head.next);
head.next.next = head;
head.next = null;
return node;
}
}
方法二:采用数组
就是将链表中的值依次放入数组中,在数组中判断回文应该非常简单了吧,只需要判断左下标的位置是否大于右下标即可
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<Integer>();
// 将链表的值复制到数组中
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))) {
return false;
}
front++;
back--;
}
return true;
}
}