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;

    }
}
相关推荐
多米Domi01140 分钟前
0x3f 第43天 黑马点评全量复习一遍 + 栈两题
开发语言·数据结构·python·算法·leetcode
sin_hielo1 小时前
leetcode 1200
数据结构·算法·leetcode
划破黑暗的第一缕曙光1 小时前
[数据结构]:链表OJ
c语言·数据结构·链表
Python_Study20251 小时前
制造业数字化转型中的数据采集系统:技术挑战、架构方案与实施路径
大数据·网络·数据结构·人工智能·架构
dazzle2 小时前
Python数据结构(六):双端队列详解
开发语言·数据结构·python
宵时待雨2 小时前
数据结构(初阶)笔记归纳8:栈和队列
数据结构·笔记
one____dream3 小时前
【算法】移除链表元素与反转链表
数据结构·python·算法·链表
睡不醒的kun3 小时前
不定长滑动窗口-基础篇(2)
数据结构·c++·算法·leetcode·哈希算法·散列表·滑动窗口
gihigo19983 小时前
MATLAB实现K-SVD算法
数据结构·算法·matlab
SJLoveIT3 小时前
架构师视角:深度解构 Redis 底层数据结构的设计哲学
数据结构·数据库·redis