题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
完整代码参考:GitHub 代码
题解
此题难度定级为简单,主要考察链表的基本操作。
解法:
思路:回文问题在字符串中可以通过设定一头一尾两个指针,分别往中间移动遍历比较。在链表中,只能往后遍历,所以可以先找到中间的节点,将后半部分的链表反转,再比较前半部分与反转后的后半部分链表的值,判断是否是回文链表。
算法:1. 首先根据快慢指针找到链表的中点,此时要注意的是,当快指针走到末尾,对奇数链表,慢指针走到中间节点,对偶数链表,慢指针走到中间位置的左一个节点(如1,2,2,1,此时慢指针位于第一个2的位置)。2.反转后半部分链表,此时,由于慢指针位于链表的中间节点(奇数链表)、中间位置偏左一个节点(偶数链表),所以需要从慢节点的后一个节点开始反转。3.比较前半部分与反转后的后半部分链表的值,此时只需要比较与依次移动两个链表的指针即可。
/**
* @Description: 1.快慢指针找到链表中点;2.反转后半部分链表;3.比较两部分
* @Date: 2019/12/26 19:21
* @param: head
* @Return:
**/
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
// 快慢指针找到链表中点
ListNode slow = head;
ListNode fast = head;
// 判断 fast.next 与 fast.next.next 是否存在
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 反转后半部分链表。注意此时后半部分为 slow.next 其后的链表
ListNode newHead = reverseList(slow.next);
// 比较两部分链表
while (newHead != null) {
if (newHead.data != head.data) {
return false;
}
newHead = newHead.next;
head = head.next;
}
return true;
}
/**
* @Description: 递归反转链表
* @Date: 2019/12/26 19:57
* @param: head
* @Return:
**/
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}