判断一个单链表是否是回文结构 要求O(N)时间复杂度 O(1)空间复杂度

没做出来 看了解析 但是思路想到了 就是只能调整链表顺序,正确答案是 把链表变成两条单链表,分别从两侧走向中间拿两个指针 分别指向两头 ,往中间走 中途有不一样的就返回false,

java 复制代码
private static  boolean  handle(Node head){
        int size = size(head);
        Node[] reserve = reserve(head, size / 2);
        Node left = reserve[0];
        Node right = reserve[1];
        while(left!=null&&right!=null){
            Integer leftvalue=left.getValue();
            Integer rightValue=right.getValue();
            if(leftvalue!=rightValue){
                return false;
            }
            left=left.next;
            right=right.next;
        }
        return true;
    }

其中一个方法是反转链表

java 复制代码
private static Node[] reserve(Node head,int start){
        Node[] result=new Node[2];
        Node pre=null;
        Node current=head;
        int count=0;
        while(current!=null){
            if(count>start) {
                Node next = current.next;
                current.next = pre;
                pre = current;
                current = next;
                continue;
            }
            current=current.next;
            count++;
        }
        result[0]=pre;
        result[1]=head;
        return result;
    }

获取链表长度 方便到时候确定从哪里开始反转

java 复制代码
private static int size(Node head){
        Node current=head;
        int count=0;
        while(current!=null){
            count++;
            current=current.next;
        }
        return count;
    }

结束

相关推荐
C雨后彩虹3 分钟前
竖直四子棋
java·数据结构·算法·华为·面试
不如自挂东南吱43 分钟前
空间相关性 和 怎么捕捉空间相关性
人工智能·深度学习·算法·机器学习·时序数据库
洛生&1 小时前
Elevator Rides
算法
2501_933513041 小时前
关于一种计数的讨论、ARC212C Solution
算法
Wu_Dylan1 小时前
智能体系列(二):规划(Planning):从 CoT、ToT 到动态采样与搜索
人工智能·算法
散峰而望1 小时前
【算法竞赛】栈和 stack
开发语言·数据结构·c++·算法·leetcode·github·推荐算法
知乎的哥廷根数学学派1 小时前
基于多尺度注意力机制融合连续小波变换与原型网络的滚动轴承小样本故障诊断方法(Pytorch)
网络·人工智能·pytorch·python·深度学习·算法·机器学习
蚊子码农1 小时前
算法题解记录-208实现Trie前缀树
运维·服务器·算法
2301_800256111 小时前
【人工智能引论期末复习】第3章 搜索求解2 - 对抗搜索
人工智能·算法·深度优先
程序猿阿伟2 小时前
《量子算法开发实战手册:Python全栈能力的落地指南》
python·算法·量子计算