234.回文链表。双百0ms

先找到中点,然后对后半部分反转,从头和中点进行比较是否相同

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head, fast = head, prev = null;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        while(slow != null){
            ListNode temp = slow.next;
            slow.next = prev;
            prev = slow;
            slow = temp;
        }
        while(head != null && prev != null){
            if(head.val != prev.val) return false;
            head = head.next;
            prev = prev.next;
        }
        return true;
    }
}
上一篇:java实现链表


下一篇:iOS LeetCode ☞ 全 O(1) 的数据结构