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;

    }
}
相关推荐
期货资管源码7 分钟前
智星期货资管子账户软件pc端开发技术栈的选择
c语言·数据结构·c++·vue
ValhallaCoder12 分钟前
Day49-图论
数据结构·python·算法·图论
宵时待雨19 分钟前
数据结构(初阶)笔记归纳5:单链表的应用
c语言·开发语言·数据结构·笔记·算法
D_FW20 分钟前
数据结构第七章:查找
数据结构
好奇龙猫25 分钟前
【大学院-筆記試験練習:线性代数和数据结构(12)】
数据结构·线性代数
kklovecode25 分钟前
数据结构---顺序表
c语言·开发语言·数据结构·c++·算法
sin_hielo26 分钟前
leetcode 1292(二维前缀和)
数据结构·算法·leetcode
Watermelo61729 分钟前
面向大模型开发:在项目中使用 TOON 的实践与流式处理
javascript·数据结构·人工智能·语言模型·自然语言处理·数据挖掘·json
小龙报1 小时前
【算法通关指南:算法基础篇 】贪心专题之简单贪心:1.最大子段和 2.纪念品分组
c语言·数据结构·c++·算法·ios·贪心算法·动态规划
AlenTech1 小时前
148. 排序链表 - 力扣(LeetCode)
数据结构·leetcode·链表