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;
        }
相关推荐
lxysbly22 分钟前
安卓PCE模拟器下载指南:用手机玩 PC-Engine / TurboGrafx 经典
android·智能手机
only-qi26 分钟前
leetcode2. 两数相加
算法·leetcode
2401_841495642 小时前
【LeetCode刷题】寻找重复数
数据结构·python·算法·leetcode·链表·数组·重复数
Digitally2 小时前
哪款应用最适合将数据从安卓手机传输到 iPhone?
android·智能手机·iphone
Java小白,一起学习3 小时前
新版onenet云平台数据流对接,包括设备端MQTT和应用端API
android·物联网
leoufung3 小时前
LeetCode 120. Triangle:从 0 分到 100 分的思考过程(含二维 DP 与空间优化)
linux·算法·leetcode
走在路上的菜鸟4 小时前
Android学Flutter学习笔记 第一节 Android视角认知Flutter(View,intent,Async UI)
android·学习·flutter
一起搞IT吧4 小时前
相机Camera日志实例分析之十二:相机Camx【萌拍后置zoom拍照】单帧流程日志详解
android·c++·数码相机·智能手机
冬奇Lab4 小时前
一次 Android 车机黑屏问题的深度剖析:当显示驱动遇上中断风暴
android·性能优化·debug
兮动人4 小时前
Fatal error: Uncaught think\exception\ErrorException: SourceGuardian Loade
android·php