234. Palindrome list of leetcode

Time:2020-5-19

234. Palindrome list

Please judge whether a linked list is palindrome linked list.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Idea: use the speed pointer to find out the intermediate nodes, and then flip them one by one for comparison. If it is an odd number of nodes that are flipped, there will be one more node than the first half. In order to judge the convenience, I counted the length of the first half of nodes. The first half of the comparison shall prevail.


/**
 * 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;
        }
        Listnode q = head; // fast node
        Listnode s = head; // slow node
        Int POS = 0; // calculate the length of the first half node
        //Intermediate node s found
        while(q!=null&&q.next!=null){
            pos++;
            s=s.next;
            q=q.next.next;
        }
        //Flip back half node
        ListNode rec=null;
        while(s!=null){
            ListNode temp=s.next;
            s.next=rec;
            rec=s;
            s=temp;
        }
        //One by one comparison, if there is an inequality, return false directly
        while(pos-->0){
            if(rec.val!=head.val){
                return false;
            }
            rec=rec.next;
            head=head.next;
        }
        return true;        
    }
}