Leetcode 234. 回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true


思路:将链表的后半段翻转,然后跑一半,看指向的值是否相等,不是则返回false

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null)
            return true;

        int count=0;
        int sum1=0,sum2=0;
        ListNode temp=head;
        while(temp!=null)
        {
            count++;
            temp=temp.next;
        }
    
        int mid=count/2;
        ListNode temp1=head;

        for(int i=0;i<mid;i++)
            temp1=temp1.next;

        ListNode pre=temp1;
        ListNode pNode=temp1.next;
        ListNode next=pNode;
        
        while(pNode!=null)
        {
            next=pNode.next;
            pNode.next=pre;
            pre=pNode;
            pNode=next;
        }
        
        for(int i=0;i<mid;i++)
        {
            
            if(head.val!=pre.val)
                return false;

            head=head.next;
            pre=pre.next;
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/tijie/p/9931563.html