234. Palindrome Linked List

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

Example 1:code

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

Input: 1->2->2->1 Output: trueio

思路

由於題目要求用O(1)的空間, 因此首先找到中間點, 而後反轉後半部分的鏈表, 而後和前半段鏈表對比.
另一種方法能夠用一個stack, 找到中點以後將中點以後的數字都加進去而後一個一個拿出來.ast

複雜度

時間O(n) 空間O(1)class

代碼

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;
    }
}
相關文章
相關標籤/搜索