【LeetCode-简单题】234. 回文链表

题目

在这里插入图片描述

题解一:将链表转换为数组,在判断回文

/**
     * 将链表数据复制到  数组当中
     * @param head
     * @return
     */
    public static boolean isPalindrome(ListNode head) {

        if (head == null||head.next == null) {
            return true;
        }

        //复制数组
        List<Integer> nums = new ArrayList<>();

        ListNode cur = head;
        while (cur!= null){
            nums.add(cur.val);
            cur = cur.next;
        }

        //判断回文
        int before = 0;
        int last = nums.size() -1 ;

        while (before < last){
            if (nums.get(before).equals(nums.get(last))) {
                before++;
                last--;
                continue;
            }else {
                return false;
            }

        }
        return true;

    }

题解二: 快慢指针

慢指针一次走一步,快指针一次走两步,快慢指针同时出发。当快指针移动到链表的末尾时,慢指针恰好到链表的中间。通过慢指针将链表分为两部分。

/**
     * 快慢指针
     * @param head
     * @return
     */
    public static boolean isPalindrome(ListNode head) {

        if (head == null || head.next == null) {
            return true;
        }

        ListNode fast = head;//快指针
        ListNode slow = head;//慢指针

        //寻找最中间的元素  条件是快指针提前走到null
        while (fast.next != null&&fast.next.next != null){
             fast = fast.next.next;
            slow = slow.next;
        }

        ListNode la = slow.next;//记录中间节点
        //将中间节点往后的元素进行翻转
        ListNode reverse = reverse(la);

        //将翻转后的链表和前半段对比
        while (reverse!=null){
            if (reverse.val != head.val ) {
                return false;
            }
            reverse = reverse.next;
            head = head.next;
        }
        return  true;

    }
    //翻转链表
    private static ListNode reverse(ListNode head){
        // 递归到最后一个节点,返回新的新的头结点
        if (head.next == null) {
            return head;
        }
        ListNode newHead =  reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值