Leetcode234.判断是否是回文单链表

题目描述

思路,把单链表转化为ArrayList,然后比较前后两个数是否相等。

java 复制代码
    class Solution {
        public boolean isPalindrome(ListNode head) {
            if (head == null) {
                return false;
            }
            List<Integer> valList = new ArrayList<Integer>();
            ListNode tmp = head;
            while (tmp != null) { 
                valList.add(tmp.val); //把单链表节点的数值,存储到ArrayList中,方便比较。
                tmp = tmp.next;
            }
            /**
             * 1. 只比较一半:(valList.size() - 1) / 2
             * 2. 小于等于
             */
            for (int i = 0; i <= (valList.size() - 1) / 2; i++) { //注意这里的小于等于
                if (valList.get(i) != valList.get(valList.size() - 1 - i)) {
                    return false;
                }
            }
            return true;
        }
    }

如果用双指针的写法,代码如下:

java 复制代码
        public boolean isPalindromeWithDoublePoint(ListNode head) {
            if (head == null) {
                return false;
            }
            List<Integer> valList = new ArrayList<Integer>();
            ListNode tmp = head;
            while (tmp != null) {
                valList.add(tmp.val); //把单链表节点的数值,存储到ArrayList中,方便比较。
                tmp = tmp.next;
            }

            int front = 0;
            int back = valList.size() - 1;
            while (front < back) {
                if (valList.get(front) != valList.get(back)) {
                    return false;
                }
                back--;
                front++;
            }
            return true;
        }
相关推荐
2601_962066491 小时前
【Sql Server】Update中的From语句,以及常见更新操作方式
android·java·数据库
用户69371750013847 小时前
曾经安卓开发人手一个的 EventBus,为什么现在没人爱用了?
android·android studio
CoderYanger8 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
九皇叔叔9 小时前
MySQL ORDER BY 性能优化详解:Using filesort、联合索引、ASC/DESC 与覆盖索引
android·adb
OriginCoding9 小时前
用 AI Agent 协作完成一个 Android TOTP 应用:从需求边界到 v1.0.0
android·ai编程
Navigator_Z10 小时前
LeetCode //C - 1221. Split a String in Balanced Strings
c语言·算法·leetcode
杉氧12 小时前
React 灵魂:深入剖析 Hooks 与副作用(Side Effects)陷阱
android·前端·react native
又见情义13 小时前
RK3568 + RTL8211F 网络唤醒(WOL)功能适配全记录
android·网络·驱动开发
用户09340777351413 小时前
HarmonyOS WPS Open SDK 实践:registerApp 鉴权与就绪门禁
android·typescript·harmonyos
jike_202613 小时前
会议离线录音APP:无网络记录能力对比
android·智能手机·语音识别