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;
        }
相关推荐
东坡大表哥3 小时前
【Ubuntu】Ubuntu 20.04 LTS → 22.04 LTS 升级实录
android·linux·ubuntu
不要试图纠正别人5 小时前
IdleHandler 一次都不跑,问题不在主线程忙
android·性能优化
booboosui5 小时前
记忆装不下时谁删:500 条上限与每回合十行索引
android
好的佩奇19 小时前
Dart 之 JSON
android·flutter·dart
_祝你今天愉快20 小时前
Android 事件传递机制:[一] 事件分发机制详解
android
旖旎夜光1 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
Digitally1 天前
如何将电脑上的联系人传输到安卓手机(4 种方法)
android
木井巳1 天前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
Navigator_Z1 天前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Carson带你学Android1 天前
移动开发周报 :一句话出 App、低端机跑 Gemini、手机写代码
android·ai编程