LeetCode-234-回文链表

LeetCode-234-回文链表

在这里插入图片描述

思路

1.数组法

把链表中的数据复制到数组中,然后使用两个指针从首尾进行比较
时间复杂度O(n),空间复杂度O(n)

2.翻转链表法

可以把后半部分的链表进行翻转,然后使用两个指针从首部和中间开始遍历进行比较
时间复杂度O(n),空间复杂度O(1)

代码

//数组法
 public boolean isPalindrome(ListNode head) {
        List<Integer> list=new ArrayList<>();
        ListNode p=head;
        while(p!=null){
            list.add(p.val);
            p=p.next;
        }
        int l=0,r=list.size()-1;
        while(l<r){
            if(list.get(l)!=list.get(r))return false;
            l++;
            r--;
        }
        return true;
    }



//翻转链表法
    public boolean isPalindrome(ListNode head) {
        if(head==null)return true;
        ListNode mid=findMiddle(head);
        ListNode n1=head;
        ListNode n2=reverseList(mid.next);
        while(n2!=null){
            if(n1.val!=n2.val){
                reverseList(mid.next);
                return false;
            }
            n1=n1.next;
            n2=n2.next;
        }
        return true;
    }
    public ListNode reverseList(ListNode head){
        ListNode cur=null;
        ListNode pre=head;
        while(pre!=null){
            ListNode t=pre.next;
            pre.next=cur;
            cur=pre;
            pre=t;
        }
        return cur;
    }
    public ListNode findMiddle(ListNode head){
        ListNode slow=head;
        ListNode fast=head;
        while(fast.next!=null&&fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值