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

结束

相关推荐
数据潜水员32 分钟前
C#基础语法
java·jvm·算法
鸽子炖汤39 分钟前
LRC and VIP
c++·算法·图论
鑫鑫向栄1 小时前
[蓝桥杯]机器人塔
数据结构·c++·算法·蓝桥杯
暴力求解1 小时前
C语言---动态内存管理、柔性数组
c语言·开发语言·算法
_Itachi__2 小时前
LeetCode 热题 100 208. 实现 Trie (前缀树)
算法·leetcode·职场和发展
闻闻不会编程2 小时前
74. 搜索二维矩阵 (力扣)
算法·leetcode·矩阵
弥彦_2 小时前
线段树刷题记录
数据结构·c++·算法
凤年徐2 小时前
【数据结构初阶】顺序表的应用
c语言·开发语言·数据结构·c++·笔记·算法·顺序表
智驱力人工智能3 小时前
高密爆炸警钟长鸣:AI为化工安全戴上“智能护盾”
人工智能·算法·安全·重构·边缘计算·高密爆炸·高密化工厂
海码0073 小时前
【Hot 100】70. 爬楼梯
数据结构·c++·算法·leetcode·动态规划·hot100