234.回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为

回文链表。如果是,返回 true ;否则,返回 false

一:

复杂度:n n

java 复制代码
puclic boolean isPalindrome(ListNode head){
    // 使用集合而不是array,可以避免创建数组前要先获取链表的长度问题
    List<Integer> list = new ArrayList<>();
    while(head != null){
        list.add(head.val);
        head = head.next;
    }
    int l = 0, r = list.size() - 1;
    while(l < r){
        if(list.get(l++) != list.get(r--)) return false;
    }
    return true;
}

二:

将链表的后半部分反转,判断前后部分是否相等

复杂度:n 1

java 复制代码
class Solution {
    public boolean isPalindrome(ListNode head) {
       //  
        int len = 0;
        ListNode pre = head;
        while(pre != null){
            len++;
            pre = pre.next;
        }
        
        // if(len != 1 && len % 2 == 1) return false;
        pre = head;
        for(int i = 0; i < len / 2; i++){
            pre = pre.next;
        }
        ListNode pre0 = pre, next = pre.next;
        pre0.next = null;
        while(next != null){
            pre0 = next;
            next = pre0.next;
            pre0.next = pre;
            pre = pre0;
        }
        while(pre != null){
            if(head.val != pre.val) return false;
            head = head.next;
            pre = pre.next;
        }
        return true;

    }
}
相关推荐
艾莉丝努力练剑3 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途4 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
秋说9 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen9 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
risc12345611 小时前
BKD 树(Block KD-Tree)Lucene
java·数据结构·lucene
kk_stoper11 小时前
如何通过API查询实时能源期货价格
java·开发语言·javascript·数据结构·python·能源
秋说11 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法
遇见尚硅谷13 小时前
C语言:20250714笔记
c语言·开发语言·数据结构·笔记·算法
恸流失15 小时前
java基础-1 : 运算符
java·开发语言·数据结构
yu20241116 小时前
【【异世界历险之数据结构世界(二叉树)】】
数据结构·算法