题目描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数 0≤n≤10^5 ,链表中每个节点的值满足 ∣val∣≤10^7
实现代码&求解思路
import java.util.*;
public class Solution {
//反转链表指针 fast-template
public ListNode reverse(ListNode head) {
//前序节点
ListNode prev = null;
while (head != null) {
//断开后序
ListNode next = head.next;
//指向前序
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public boolean isPail (ListNode head) {
//空链表直接为回文
if(head == null)
return true;
//准备快慢双指针
ListNode slow = head;
ListNode fast = head;
//双指针找中点
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//中点处反转
slow = reverse(slow);
fast = head;
while (slow != null) {
//比较判断节点值是否相等
if (slow.val != fast.val)
return false;
fast = fast.next;
slow = slow.next;
}
return true;
}
}