先利用快慢指针将链表一分为2,后半部分链表进行反转,然后两个链表一一比对就可以判断是否回文了
/*** 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) {//用快慢指针将链表一分为二ListNode slow=head;ListNode fast=head.next;while (fast != null && fast.next != null) {slow=slow.next;fast=fast.next.next;}//反转后半部分链表ListNode secondPartNode = this.reverse(slow.next);//前后部分比对看是否是回文链表ListNode firstPartNode=head;while (firstPartNode != null && secondPartNode != null) {if (firstPartNode.val != secondPartNode.val) {return false;}firstPartNode=firstPartNode.next;secondPartNode=secondPartNode.next;}return true;}private ListNode reverse(ListNode head){if (head == null) {return head;}ListNode pre=null;while (head != null) {ListNode temp=head.next;head.next=pre;pre=head;head=temp;}return pre;}
}