回文链表
题目:
请判断一个链表是否为回文链表。
思想:
通过快慢指针找到链表的中间节点,把前半部分链表翻转过来,和后半部分链表进行比较(如果节点数为奇数,去除后边部分第一个节点),如果相同,则为回文,返回true;否则返回false。
代码:
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
//快慢指针找到链表的中点
ListNode fast = head.next.next;
ListNode slow = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//翻转链表前半部分
ListNode pre = null;
ListNode next = null;
while (head != slow) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
//如果是奇数个节点,去掉后半部分的第一个节点。
if (fast != null) {
slow = slow.next;
}
//回文校验
while (pre != null) {
if (pre.val != slow.val) {
return false;
}
pre = pre.next;
slow = slow.next;
}
return true;
}
}