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;
        }
相关推荐
2501_916007476 小时前
Fastlane 结合 开心上架(Appuploader)命令行实现跨平台上传发布 iOS App 的完整方案
android·ios·小程序·https·uni-app·iphone·webview
listhi5208 小时前
Vue.js 3的组合式API
android·vue.js·flutter
用户69371750013848 小时前
🚀 Jetpack MVI 实战全解析:一次彻底搞懂 MVI 架构,让状态管理像点奶茶一样丝滑!
android·android jetpack
2501_9159184110 小时前
iOS 上架应用市场全流程指南,App Store 审核机制、证书管理与跨平台免 Mac 上传发布方案(含开心上架实战)
android·macos·ios·小程序·uni-app·cocoa·iphone
峥嵘life10 小时前
Android EDLA 打开5G热点失败分析解决2
android·5g
ZHE|张恒11 小时前
LeetCode - 寻找两个正序数组的中位数
算法·leetcode
消失的旧时光-194311 小时前
webkitx(Android WebView 最佳实践库)--> 上
android·webview
安卓兼职framework应用工程师12 小时前
android 15.0 app应用安装黑名单
android·pms·install·rom·安装黑名单