【LC】234. 回文链表

题目描述:

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false

示例 1:

复制代码
输入:head = [1,2,2,1]
输出:true

示例 2:

复制代码
输入:head = [1,2]
输出:false

题解:

先转成列表再比较首尾的值

复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int left = 0, right = list.size() - 1;
        while (left <= right) {
            if (!list.get(left).equals(list.get(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
相关推荐
lUie INGA5 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
geBR OTTE5 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu6 小时前
博客系统UI自动化测试报告
java
不爱吃炸鸡柳6 小时前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
Aurorar0rua6 小时前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy7 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
布谷歌7 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
6Hzlia7 小时前
【Hot 100 刷题计划】 LeetCode 739. 每日温度 | C++ 逆序单调栈
c++·算法·leetcode
eLIN TECE8 小时前
springboot和springframework版本依赖关系
java·spring boot·后端