leetcode 234. 回文链表 java

题目:

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

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(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) {    //画个图走一遍就懂了
        if(head == null || head.next == null) {
            return true;
        }
        ListNode slow = head, fast = head;    //快慢指针找到链表的中间位置
        ListNode pre = head, prepre = null;//专门设立两个指针用于反转链表
        while(fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
            pre.next = prepre;    //反转前半部分链表
            prepre = pre;
        }
        if(fast != null) {    //对准中点
            slow = slow.next;
        }
        while(pre != null && slow != null) {
            if(pre.val != slow.val) {
                return false;
            }
            pre = pre.next;
            slow = slow.next;
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/yanhowever/p/11926471.html