7.Palindrome Linked List(回文链表)

Level:

​  Easy

题目描述:

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?

思路分析:

​  由题意知,我们要判断一个链表是不是回文结构,并且时间复杂度为O(n),额外的空间复杂度为O(1)。那么我们只能在原地进行判断,我们可以将链表分成左右两部分,然后将右部分链表进行原地反转,反转完成后我们分别从最左端和最右段开始遍历链表,并且实时判断左右两部分链表对应的节点值是否相等,如果不等那就返回false,如果遍历能够走到最后,那么就返回true。这样可以在满足题目要求的情况下,求出问题的解。

代码:

/**
 * 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;
        if(head.next==null)
            return true;
        ListNode n1=head;
        ListNode n2=head;
        //设置一个满指针和一个快指针,找到链表的中间节点,用来将链表化为左右两部分
        while(n1.next!=null&&n1.next.next!=null){
            n1=n1.next.next;
            n2=n2.next;
        }
        n2=n1.next; //右部分
        n1.next=null //左右断开
        ListNode n3=null;
        while(n2!=null){//反转右部分链表
            n3=n2.next;
            n2.next=n1;
            n1=n2;
            n2=n3;
        }
        n3=n1;//保存最右的节点,以便最后回复链表的结构
        n2=head;
        while(n1!=null&&n2!=null){//判断链表是否为回文结构
            if(n1.val!=n2.val)
                return false;
            n1=n1.next;
            n2=n2.next;
        }
        n1=n3.next;
        n3.next=null;
        while(n1!=null){//恢复链表结构
            n2=n1.next;
            n1.next=n3;
            n3=n1;
            n1=n2;
        }
        return true;
    }
}
posted @ 2019-04-13 22:08  yjxyy  阅读(170)  评论(0编辑  收藏  举报