判断一个单链表是否是回文结构 要求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;
    }

结束

相关推荐
好家伙VCC19 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle21 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx1 天前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐1 天前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸1 天前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
一只懒洋洋1 天前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类
方案开发PCBA抄板芯片解密1 天前
什么是算法:高效解决问题的逻辑框架
算法
songx_991 天前
leetcode9(跳跃游戏)
数据结构·算法·游戏
小白狮ww1 天前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥1 天前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud