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;
        }
相关推荐
louisgeek20 分钟前
Android Studio 和 Git
android
鱼儿也有烦恼3 小时前
快速学完 LeetCode top 1~50
leetcode·algorithm
solo_995 小时前
Android Event 日志完全指南
android
孙晓鹏life5 小时前
MySQL-Seconds_behind_master的精度误差
android·mysql·adb
雨白6 小时前
C 语言文件操作核心
android
退休倒计时7 小时前
【每日一题】LeetCode 17. 电话号码的字母组合 TypeScript
算法·leetcode·typescript
鱼儿也有烦恼7 小时前
01.搭建Android Studio开发环境
android·android studio
临沂堇8 小时前
刷题日志 | LeetCode Hot 100 双指针
算法·leetcode·职场和发展
XWalnut8 小时前
LeetCode刷题 day29
java·算法·leetcode
m0_738120728 小时前
PHP代码审计基础——面向对象(四)
android·开发语言·网络·安全·github·php