# 数据结构与算法 | 回文链表检测

pexels-photo-747964

## 回文链表

``````Input: 1->2
Output: false
``````

``````Input: 1->2->2->1
Output: true
``````

### 解法一

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

return true;
}
ListNode newCurr = null;
ListNode newPrev = null;
while(curr != null){
newCurr = new ListNode(curr.val);
newCurr.next = newPrev;
newPrev = newCurr;
curr = curr.next;
}

ListNode p1 = newCurr;

while(p2 != null && p2 != null){
if(p2.val != p1.val){
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}
}

``````

LeetCode性能测试：

Runtime: 3 ms, faster than 24.01% of Java online submissions forPalindrome Linked List.

### 解法二

`A -> B -> C -> C -> B -> A` 反转得到 `A -> B -> C -> C <- B <- A`，以前半部分为基准的话，会出现 null 指针的异常。

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

return true;
}

// 先找到中间节点，slow最后的结果就是中间节点

for(ListNode curr = slow; slow != null; ){
if(fast == null || fast.next == null){
break;
}else{
fast = fast.next.next;
}
slow = slow.next;
}

// 从slow开始，对后链表后半部分进行反转
ListNode prev = null;
ListNode curr = slow;
ListNode next = null;

while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}

// 对前后两个部分进行比较
ListNode p2 = prev;

while(p2 != null){
if(p1.val != p2.val){
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}
}
``````

LeetCode性能测试：

Runtime: 1 ms, faster than 93.05% of Java online submissions forPalindrome Linked List.

### 解法三

• 定义左右两个指针，左指针向有移动，"右指针向左移动"，对比左右两个指针是否配置。
• 我们这里是单链表，右指针怎么向左移动呢？这里通过递归的方式，当递归函数一层一层返回时，变相地实现了"右指针左移"的思路。

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

private ListNode left;

}

private boolean isPalindromeUtil(ListNode right){

// 当指向NULL时，停止递归
if (right == null){
return true;
}

// 向右移动指针，递归调用
boolean isp = isPalindromeUtil(right.next);
if (isp == false){
return false;
}

// 比较左右指针是否匹配
boolean isp1 = (right.val == left.val);

// 移动左指针
left = left.next;

return isp1;
}
}
``````

LeetCode性能测试：

Runtime: 3 ms, faster than 22.70% of Java online submissions forPalindrome Linked List.