1. 题目原址
https://leetcode.com/problems/palindrome-linked-list/
2. 题目描述
3. 题目大意
给定一个链表,判断链表是否是回文链表
4. 解题思路
- 步骤一:将链表的前半部分进行反转。使用快慢指针,当快指针走到链表末尾的时候,链表就不需要反转了。
- 步骤二:然后从中间开始向两边进行遍历。
5. AC代码
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode slow = head, fast = head;
ListNode newHead = null;
while(fast != null && fast.next != null) {
fast = fast.next.next;
ListNode next = slow.next;
slow.next = newHead;
newHead = slow;
slow = next;
}
if(fast != null) slow = slow.next;
while (slow != null) {
if(slow.val != newHead.val) return false;
slow = slow.next;
newHead = newHead.next;
}
return true;
}
}