LeetCode 234 Palindrome Linked List

题目描述

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

Follow up:

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

分析

O(n) time and O(1) space的解法:

  1. 找到链表中点
  2. 将后半段链表翻转
  3. 对比两段链表

说明:不用管链表是奇数还是偶数,如果链表长度是偶数,那么翻转后,前段和后段链表长度相等;如果是奇数,后段链表长1个结点,所以只需要判断前段结点是否遍历结束。

代码

    public boolean isPalindrome(ListNode head) {

        if (head == null || head.next == null) {
            return true;
        }

        ListNode slow = head;
        ListNode fast = head;

        // 找到链表中点
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // 翻转后段链表
        ListNode tail = reverseList(slow);

        while (head != slow) {
            if (head.val != tail.val) {
                return false;
            }
            head = head.next;
            tail = tail.next;
        }

        return true;
    }

    public ListNode reverseList(ListNode head) {

        if (head == null) {
            return null;
        }

        if (head.next == null) {
            return head;
        }

        ListNode tail = head.next;
        ListNode reversed = reverseList(head.next);

        // 前后翻转tail和head
        tail.next = head;
        head.next = null;

        return reversed;

    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50260675
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞