题目
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解题思路
本题要判断一个链表是否回文的
- 可以从中间向两边,依次判断是否相同
- 可以从两边向中间,依次判断是否相同
本题提供一个单向链表,只能向一个方向移动,所以需要构建一种能够同时向两个方向移动的结构
方法1:双指针,时间复杂度O(n),空间复杂度O(n)
- 遍历链表,将数据存放在list中
- 使用双指针从两边向中间位置移动,依次判断是否相同
本题希望能提供一种空间复杂度是O(1)的解决方案
方法2:快慢指针,时间复杂度O(n),空间复杂度O(1)
- 使用快慢指针找到链表的中间位置,链表被分为左右两部分
- 翻转右边部分链表,使其可以从链表尾部向链表中间移动
- 从链表的头部和尾部分别向中间位置移动,依次判断是否相同
代码
方法1:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int left = 0, right = list.size() - 1;
while (left < right) {
if (!list.get(left++).equals(list.get(right--))) return false;
}
return true;
}
}
方法2:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tail = reverse(slow);
while (tail != null) {
if (tail.val != head.val) return false;
tail = tail.next;
head = head.next;
}
return true;
}
private ListNode reverse(ListNode node) {
ListNode prev = null;
while (node != null) {
ListNode next = node.next;
node.next = prev;
prev = node;
node = next;
}
return prev;
}
}