223.Palindrome Linked List-回文链表(中等题)

回文链表

  1. 题目

    设计一种方式检查一个链表是否为回文链表。

  2. 样例

    1->2->1 就是一个回文链表。

  3. 挑战

    O(n)的时间和O(1)的额外空间。

  4. 题解

    使用快慢指针找到链表的中点,然后以该节点为头节点进行反转,再从头进行双指针遍历判断。
    如1->2->3->2->1->null,找到中间节点为3,对3->2->1->null进行翻转得到1->2->1->2->3->null,再用双指针分别指向两个1,进行遍历判断,直至结束或者发现值不相等的节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a boolean
     */
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null)
        {
            return true;
        }
        ListNode low = head;
        ListNode fast = head.next;
        ListNode newHalfHead = null;
        while (fast != null && fast.next != null && fast.next.next != null)
        {
            fast = fast.next.next;
            low = low.next;
        }
        newHalfHead = reverse(low.next);
        low.next = newHalfHead;
        while (head != low.next)
        {
            if (head.val != newHalfHead.val)
            {
                return false;
            }
            head = head.next;
            newHalfHead = newHalfHead.next;
        }
        return true;
    }

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

Last Update 2016.11.5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值