请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//快慢指针法,找到中间节点
//将链表一分为二
//将后半段链表与前半段链表进行比较
//看是否为回文链表
//要对链表进行一个校验
if(head == null || head.next == null){
return true;
}
ListNode p = new ListNode(-1);
p.next = head;
ListNode fast = p;
ListNode slow = p;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
//定义后半段链表
//second指针置于后半段链表的开始
ListNode second = slow.next;
//断开链表
slow.next = null;
//将slow指针置于前半段链表的开始
slow = p.next;
//反转后半段链表
ListNode pre = null;
while(second != null){
ListNode tempNext = second.next;
second.next = pre;
pre = second;
second = tempNext;
}
//判断两段链表是否相同
//若为奇数时,前半段比后半段多1,直接以后半段为基准比较即可
while(pre != null){
if(slow.val != pre.val){
return false;
}
slow = slow.next;
pre = pre.next;
}
return true;
}
}