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

结束

相关推荐
明月看潮生1 小时前
青少年编程与数学 02-018 C++数据结构与算法 06课题、树
数据结构·c++·算法·青少年编程·编程与数学
小指纹1 小时前
动态规划(一)【背包】
c++·算法·动态规划
_安晓2 小时前
数据结构 -- 图的应用(一)
数据结构·算法·图论
阳洞洞2 小时前
leetcode 二分查找应用
算法·leetcode·二分查找
猎猎长风2 小时前
【数据结构和算法】1. 数据结构和算法简介、二分搜索
数据结构·算法
Pasregret2 小时前
模板方法模式:定义算法骨架的设计模式
算法·设计模式·模板方法模式
左灯右行的爱情2 小时前
JVM-卡表
java·jvm·算法
奋斗者1号3 小时前
逻辑回归:使用 S 型函数进行概率预测
算法·机器学习·逻辑回归
CodeJourney.4 小时前
基于DeepSeek与Excel的动态图表构建:技术融合与实践应用
数据库·人工智能·算法·excel
Gerry_Liang4 小时前
LeetCode热题100——283. 移动零
数据结构·算法·leetcode