栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

234. 回文链表(java实现)--2种解法(双指针,反转链表后半段)LeetCode

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

234. 回文链表(java实现)--2种解法(双指针,反转链表后半段)LeetCode

文章目录

题目:解法1:双指针解法2:反转链表后半段

01:递归02:不设置前驱节点03:设置前驱节点

题目: 解法1:双指针
    
    public static boolean isPalindrome(ListNode head) {
        ArrayList list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        return judge_doublePoint(list);
    }


    private static boolean judge_doublePoint(ArrayList list) {
        int l = 0, r = list.size() - 1;
        while (r > l) {
            if (!list.get(l++).equals(list.get(r--))) {
                return false;
            }
        }
        return true;
    }

时间复杂度:On

空间复杂度:On

解法2:反转链表后半段 01:递归
    
    public static boolean isPalindrome(ListNode head) {
        ListNode slow=head,fast=head;
        while (fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
    
        ListNode reverse_half = reverse_recursive(slow);
    //    ListNode reverse_half = reverse_noPre(slow);
    //    ListNode reverse_half = reverse_pre(slow);

        while (reverse_half!=null){
            if (reverse_half.val!=head.val){
                return false;
            }
            reverse_half=reverse_half.next;
            head=head.next;
        }
        return true;
    }
    
    private static ListNode reverse_recursive(ListNode head) {
        if (head==null||head.next==null){
            return head;
        }
        ListNode tail = reverse_recursive(head.next);
        head.next.next=head;
        head.next=null;
        return tail;
    }

时间复杂度:On

空间复杂度:On

02:不设置前驱节点
    private static ListNode reverse_noPre(ListNode head) {
        ListNode curr = head;
        ListNode next = curr.next;
        while (next!= null){
            ListNode nn = next.next;
            next.next=curr;
            head.next=nn;
            curr=next;
            next=nn;
        }
        return curr;
    }

时间复杂度:On

空间复杂度:O1

03:设置前驱节点
    private static ListNode reverse_pre(ListNode reversNode) {
        ListNode pre=null;
        ListNode curr = reversNode;
        while (curr!=null){
            ListNode next = curr.next;
            curr.next=pre;
            pre=curr;
            curr=next;
        }
        return pre;
    }

时间复杂度:On

空间复杂度:O1

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/735824.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号