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

结束

相关推荐
艾莉丝努力练剑11 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
秋说6 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen6 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove7 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty8 小时前
排序算法(二):插入排序
算法·排序算法
然我8 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
F_D_Z8 小时前
【EM算法】三硬币模型
算法·机器学习·概率论·em算法·极大似然估计
秋说9 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法