234. Palindrome Linked List

题目

原始地址:https://leetcode.com/problems/palindrome-linked-list/#/description

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        
    }
}

描述

给定一个单链表,判断它是不是回文的(即从前往后与从后往前内容是相同的)

分析

题目要求空间复杂度为O(1),没有要求不改变原来的链表,因此能想到的就是翻转链表的前半部分,再与后半部分比较是否相同。
分配三个指针l1,l2和l3,首先通过快慢指针的方式找到链表的中心l2(如果链表节点数为偶数,此时为左侧的中心节点),并将l2右侧的节点赋给l1,之后翻转右侧的半个链表,翻转完成后将两个链表逐个节点判断即可。注意如果原链表的长度为奇数,那么左侧链表会比右侧链表多一个节点,而这个节点就是原链表的中心节点,可以直接忽略,所以最后遍历时我们要以右侧的链表为准来判断结束。

解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode l1 = head, l2 = head, l3;
        while (l1.next != null && l1.next.next != null) {
            l1 = l1.next.next;
            l2 = l2.next;
        }
        l1 = l2.next;
        l2.next = null;
        l2 = null;
        while (l1 != null) {
            l3 = l1.next;
            l1.next = l2;
            l2 = l1;
            l1 = l3;
        }
        l1 = head;
        while (l2 != null) {
            if (l1.val != l2.val) {
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return true;
    }
}
posted @ 2017-05-05 09:33  北冥尝有鱼  阅读(89)  评论(0编辑  收藏  举报