234--Palindrome Linked List

本文介绍了两种链表回文检测方法。第一种是将链表元素存入数组再进行对比,适合初学者理解。第二种使用快慢指针技巧,反转前半部分链表,从中间向两边比较,更高效且节省空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class PalindromeLinkedList {
    /*
    解法一:可能刚开始刷题的原因,想到的老是这种简单的笨办法。
     */

    public static boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null)
            return true;
        ListNode temp=head;
        List<Integer> list=new ArrayList<>();
        while (temp!=null){
            list.add(temp.val);
            temp=temp.next;
        }
        temp=head;
        for (int i=list.size()-1;i>=0;i--){
            if (temp.val!=list.get(i).intValue())
                return false;
            temp=temp.next;
        }
        return true;
    }

   
    /*
    解法二:用快慢指针找到链表中点,同时反转前半部分,然后依次从中点向两边回文检验。
     */
    public boolean isPalindrome2(ListNode head) {
        if (head==null||head.next==null)
            return true;
        ListNode slow=head;
        ListNode fast=head.next;
        ListNode previous=null;
        ListNode next=null;
        while (fast!=null&&fast.next!=null){
            next=slow.next;
            slow.next=previous;
            previous=slow;
            slow=next;
            fast=fast.next.next;
        }
        ListNode right=slow.next;
        ListNode left=null;
        if (fast==null)
            left=previous;
        else{
            slow.next=previous;
            left=slow;
        }
        while (left!=null){
            if (left.val!=right.val)
                return false;
            left=left.next;
            right=right.next;
        }
        return true;
    }
}

 

转载于:https://www.cnblogs.com/zhangyuhao/p/11441558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值