LeetCode题解-234-回文链表

题目描述

请判断一个链表是否为回文链表。

示例1:

输入: 1->2

输出: false

示例2:

输入: 1->2->2->1

输出: true

思路

用快慢指针法得到链表的中间节点,然后以中间节点为头节点翻转后半段链表,同时遍历前半段链表和后半段链表,如果在两断链表还没有走到头的时候,有值不相等则链表不是回文的。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head, fast = head;
// 快慢指针得到中间节点slow
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode l1 = head;
// 翻转后半段链表
ListNode l2 = reverse(slow);
// 进行比较
while (l1 != null && l2 != null) {
if (l1.val != l2.val) {
return false;
} else {
l1 = l1.next;
l2 = l2.next;
}
}
return true;
}

public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = reverse(head.next);
head.next.next = head;
head.next = null;
return p;
}