Java determines whether the linked list is a palindrome structure

Title description

Given a linked list, please determine whether the linked list is a palindrome structure.

Example 1

enter

[1,2,2,1]

return value

true

For a palindrome linked list, it can be found that when the pointer node is traversing it, walking to the middle position is equivalent to walking backward from the middle,
such as 1->2->3->2->1, 1-> 2->2->1
So the part after the middle can be regarded as the reversal of the first half,
so the part after the middle can be reversed, and a linked list that is the same as the first half can be obtained, which also becomes the judgment back Text structure conditions

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 对于一个回文链表可以发现,当指针节点在对其进行遍历时,走到中间位置就等同于从中间倒着往前走
     * 如 1->2->3->2->1,1->2->2->1
     * 所以可以将中间以后的部分视为前半部分的反转
     * 因此可以将中间以后的部分进行反转,就能得到一个和前半部分相同的链表,这也变成了判断回文结构的条件
     */
    public boolean isPail (ListNode head) {
        
        if(head == null || head.next == null){
            return true;
        }
        
        ListNode fastNode = head;
        ListNode slowNode = head;
        
        while(fastNode != null && fastNode.next != null){
            fastNode = fastNode.next.next;
            slowNode = slowNode.next;
        }
        
        //针对后半段链表 进行反转
        ListNode curSlowNode = slowNode.next;
        ListNode preSlowNode = slowNode;
        ListNode tempNode = null;
        while(curSlowNode!=null){
            tempNode = curSlowNode.next;
            curSlowNode.next = preSlowNode;
            preSlowNode = curSlowNode;
            curSlowNode = tempNode;
        }
        slowNode.next = null;
        
        while(preSlowNode!=null){
            
            if(head.val != preSlowNode.val){
                return false;
            }
            
            head = head.next;
            preSlowNode = preSlowNode.next;
            
        }
        
        return true;
    }
}

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112646417