【leetcode hot 100 234】回文链表

错误解法一:正序查找的过程中,将前面的元素倒叙插入inverse链中,找到偶数中点时,对称查找。

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head.next == null){
            // 只有一个元素
            return true;
        }
        ListNode inverse=null, find=head;
        while(find != null){
            // 把find倒叙插入inverse中
            ListNode temp=find.next;
            find.next = inverse;
            inverse = find;
            find = temp;
            while(find != null && inverse != null && find.val == inverse.val){
                // 找到中点在find和find.next之间
                find = find.next;
                inverse = inverse.next;
            }
        }
        if(find==null && inverse==null ){
            return true;
        }
        return false;
    }
}

错误原因:没有考虑奇数情况

解法一:将数据转存到列表中,用双指针比较。

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();

        // 将所有数据放入list中
        while(head!=null){
            list.add(head.val);
            head=head.next;
        }

        // 使用左右指针查找
        int left=0,right=list.size()-1;
        while(left<right){
            if(list.get(left)!=list.get(right)){
                return false;
            }
            right--;
            left++;
        }
        return true;
    }
}
相关推荐
你撅嘴真丑3 小时前
第九章-数字三角形
算法
uesowys3 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder3 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮3 小时前
AI 视觉连载1:像素
算法
智驱力人工智能3 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥4 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风4 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風4 小时前
8.1 PFH&&FPFH
图像处理·算法
NEXT065 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
代码游侠5 小时前
学习笔记——设备树基础
linux·运维·开发语言·单片机·算法