1. 问题
问题描述:
Given the head
of a singly linked list, return true
if it is a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
The number of nodes in the list is in the range [1, 105]
.
0 <= Node.val <= 9
Follow up: Could you do it in O(n)
time and O(1)
space?
2. 分析
这题最容易想到的解法是:
先从 head
遍历 list
并把值依次 push
到 stack
中;
然后再遍历一次 list
, 和 stack
出栈结果对比, 如果都相同, 那么 此 list
就是回文链表.
题目最后提示用 O(1)
的空间复杂度.
也就是说用一个新的集合对象存 list 的数据是不可行的.
如果我们可以把 list 的 后半部分做一下翻转, 然后用两个指针分别指向 前和后 两部分, 顺序遍历一半 list
, 对比每个对应的元素值是否相等, 就能知道是不是 回文链表 了.
翻转单链表:
比如把 ① -> ② -> ③ -> ④ -> ⑤
转成 ① <- ② <- ③ <- ④ <- ⑤
可以通过 3 个指针: cur
, pre
, temp
实现翻转.
上图经过5步(紫色的圈, 虚线是不存在指向关系的, 这里画出只是为了对比) 实现了翻转.
单链表中, 通过 快慢指针 找到中间位置:
变量 list
, 用一个 fast 指针
每次走两步, slow 指针
每次走一步; fast
不够两步走时结束.
list.size
为奇数时: slow
会停在最中间的元素上(比如size=3
, slow
会停在第2个位置上);
list.size
为偶数时: slow
会停在最中间靠前的元素上(比如 size=4
, slow
也会停在第2个位置上).
不论 list.size
是奇数还是偶数, 我们在翻转后半部分单链表后, 遍历短的那一半单链表即可.
题解:
public boolean isPalindrome(ListNode head) {
if (head == null) {
return false;
}
if (head.next == null) {
return true;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast.next == null) {
break;
}
}
ListNode p = reverse(slow.next);
while (p != null) {
if (p.val != head.val) {
return false;
}
p = p.next;
head = head.next;
}
return true;
}
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
单链表:
// Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
3 总结
单链表是 一个基础的 数据结构.
通过 快慢指针 找单链表的中间元素,
以及 翻转单链表 都是单链表的基础操作.
这两个基础操作也是解本题的关键.