Given a singly linked list, determine if it is a palindrome.

Example 1:

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

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

思路

因为题目要求用O(1)的空间, 所以首先找到中间点, 然后反转后半部分的链表, 然后和前半段链表对比.
另外一种方法可以用一个stack, 找到中点之后将中点之后的数字都加进去然后一个一个拿出来.

复杂度

时间O(n) 空间O(1)

代码

class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null ) return true;
        ListNode fast = head, slow = head, pointer = head;;
        while (fast!= null && fast.next!= null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode newHead = slow;
        ListNode res = reverse(newHead);
        while (res!= null) {
            if (res.val != head.val) {
                return false;
            }
            res = res.next;
            head = head.next;
        }
        return true;
        
    }
    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
}

lpy1990
26 声望10 粉丝