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

leetcode-回文链表

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

leetcode-回文链表

题目:

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

解法一(利用栈):
    
    public boolean isPalindrome(ListNode head) {
        if (head.next == null){
            return true;
        }
        //使用栈来处理
        Stack stack = new Stack<>();

        List list = new ArrayList<>();

        ListNode cur = head;//辅助节点,用来遍历链表

        while (cur != null){
            list.add(cur.val);
            cur = cur.next;
        }

        //偶数情况
        if (list.size()%2 == 0){
            for (int i = 0 ; i < list.size()/2 ; i++){
                stack.push(list.get(i));
            }
            for (int i = list.size()/2; i < list.size() ; i++){
                if (list.get(i) != stack.peek()){
                    return false;
                }else stack.pop();
            }
        }
        //奇数情况
        if (list.size()%2 == 1){
            for (int i = 0 ; i < (list.size()-1)/2 ; i++){
                stack.push(list.get(i));
            }
            for (int i = (list.size()+1)/2; i < list.size() ; i++){
                if (list.get(i) != stack.peek()){
                    return false;
                }else stack.pop();
            }
        }
        return stack.empty();
    }
解法二(双指针):
  
    public boolean isPalindrome(ListNode head) {

        List list = new ArrayList<>();

        ListNode cur = head;

        while (cur != null){
            list.add(cur.val);
            cur = cur.next;
        }

        int front = 0;//前指针
        int rear = list.size()-1;//后指针

        while (front < rear){
            if (list.get(front) != list.get(rear)){
                return false;
            }
            front++;
            rear--;
        }
        return true;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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