回文链表

  

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

public static boolean isPalindrome(ListNode head){
        ListNode fast=head;
        ListNode slow=head;
        while (fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode slowHead=slow;
        ListNode reverse=reverse(slow);
        ListNode h=head;
        while (h!=slowHead){
            if(h.val!=reverse.val){
                return false;
            }
            h=h.next;
            reverse=reverse.next;
        }
        return true;
    }
View Code
static ListNode reverse(ListNode head){
        ListNode curr=head;
        ListNode pre=null;
        while (curr!=null){
            ListNode temp=curr.next;
            curr.next=pre;
            pre=curr;
            curr=temp;
        }
        return pre;
    }
View Code
@Data
    static class ListNode{
        private int val;
        private ListNode next;

        public ListNode(int value){
            this.val=value;
        }
    }
View Code

  主要思路是

  1.先通过快慢指针(慢指针一次走一步,快指针一次走2步),找到后半段链表。

  2.把后半段链表反转。

  3.对比前半段链表和后半段链表是否一样,不一样返回false。

原文地址:https://www.cnblogs.com/wuyouwei/p/11766384.html