回文链表

这篇博客探讨了如何检查链表是否为回文的三种不同算法:使用双指针遍历数组、递归以及快慢指针。每种方法都有其独特之处,双指针法简单直接,递归法利用了链表的特性,而快慢指针则通过翻转一半链表来简化比较。这些算法展示了在处理链表问题时的不同思路。

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

题目来源

回文链表

题目描述

在这里插入图片描述

解答一

将值复制到数组之后用双指针法(使用集合List存储链表中的元素,然后双指针,一个从头开始,一个从结尾开始进行比较)

class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> list=new ArrayList<>();
        ListNode cur=head;
        while(cur!=null){
            list.add(cur.val);
            cur=cur.next;
        }
        int i=0;
        int j=list.size()-1;
        while(i<j){
            if(!list.get(i).equals(list.get(j))){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

解答二(递归)

class Solution {
    private ListNode frontPointer;
    public boolean isPalindrome(ListNode head) {
        frontPointer=head;
        return recuriselyCheck(head);
    }
    private boolean recuriselyCheck(ListNode currentNode){
        if(currentNode!=null){
            if(!recuriselyCheck(currentNode.next)){
                return false;
            }
            if(currentNode.val!=frontPointer.val){
                return false;
            }
            frontPointer=frontPointer.next;
        }
        return true;
    }
}

解答三:快慢指针

在这里插入图片描述

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null){
            return true;
        }
        ListNode first=endOfFirst(head);
        ListNode second=revserse(first.next);
        //判断是否为回文
        ListNode p1=head;
        ListNode p2=second;
        boolean result=true;
        while(result&&p2!=null){
            if(p1.val!=p2.val){
                result=false;
            }
            p1=p1.next;
            p2=p2.next;
        }
        first.next=revserse(second);
        return result;
    }
    private ListNode revserse(ListNode head){
        ListNode prev=null;
        ListNode cur=head;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=prev;
            prev=cur;
            cur=next;
        }
        return prev;
    }
    private ListNode endOfFirst(ListNode head){
        ListNode slow=head;
        ListNode fast=head;
        while(fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        return slow;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值