234. Palindrome Linked List

原题链接:https://leetcode.com/problems/palindrome-linked-list/description/
实现如下:

/**
 * Created by clearbug on 2018/2/26.
 *
 * 哎😔,这又是一道比较简单的题目,可以我依然是没有想出解决方法来,然后下面的方法是看了人家评论区的实现而已!
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();

    }

    public boolean isPalindrome(ListNode head) {
        ListNode fast = head, slow = head;
        // 借助双指针,先找到该单链表的中间位置
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 现在 slow 指针已经处于单链表的中间位置了,然后将该单链表后半部分坐一下反转
        fast = head;
        slow = reverse(slow);
        while (slow != null) {
            if (fast.val != slow.val) {
                return false;
            }
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    private ListNode reverse(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

}
posted @ 2018-04-05 21:42  optor  阅读(157)  评论(0)    收藏  举报