234. Palindrome Linked List

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

Follow up:
Could you do it in O(n) time and O(1) space?

/**
 * 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) return true;
        ListNode slow = findmiddle(head);
        ListNode subhead = slow.next;
        slow.next = null;
        subhead = reverse(subhead);
        while(head != null && subhead != null && head.val == subhead.val){
            head = head.next;
            subhead = subhead.next;
        }
        if(subhead == null) return true;
        return false;
    }
    private static ListNode findmiddle(ListNode head){
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    private static ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = prev;
            prev = head;
            head = tmp;
        }

        return prev;
    }
}

findmiddle返回slow指针,指的是前半段最后一个node的位置,随后断开。后半段reverse,再把两段作比较,后半段长度只会小于等于前半段,所以后半段比较完就说明是palindrome。

posted @ 2019-08-22 04:48  Schwifty  阅读(126)  评论(0编辑  收藏  举报