234. 回文链表
// 要实现 O(n) 的时间复杂度和 O(1) 的空间复杂度,需要翻转后半部分
// 根据快慢指针,找到链表的中点
//反转后面的链表
//依次比较
Difficulty: 简单
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false```
**示例 2:**
输入: 1->2->2->1
输出: true
**进阶:**
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
#### Solution
Language: **Java**
```java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
slow = reverseList(slow.next);
while (slow != null) {
if (head.val != slow.val) {
return false;
}
head = head.next;
slow = slow.next;
}
return true;
}
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode here = head;
while (here!=null) {
ListNode temp = here.next;
here.next = pre;
pre = here;
here = temp;
}
return pre;
}
}