【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;
    }
}
相关推荐
scx2013100436 分钟前
20250822 组题总结
c++·算法
智驱力人工智能1 小时前
智慧工厂烟雾检测:全场景覆盖与精准防控
人工智能·算法·安全·智慧城市·烟雾检测·明火检测·安全生产
浩少7023 小时前
LeetCode-17day:贪心算法
算法·leetcode·贪心算法
weixin_516875654 小时前
力扣 30 天 JavaScript 挑战 第37天 第九题笔记 知识点: 剩余参数,拓展运算符
javascript·笔记·leetcode
mashanshui7 小时前
Https之(二)TLS的DH密钥协商算法
算法·https·tls·dh·ecdhe
wearegogog12310 小时前
MATLAB的脉搏信号分析预处理
算法·matlab
fs哆哆10 小时前
在VB.net中一维数组,与VBA有什么区别
java·开发语言·数据结构·算法·.net
wjt10202010 小时前
机器学习--续
算法·机器学习
牵星术小白11 小时前
【GNSS基带算法】Chapter.2 相干积分与非相干积分
算法
哇哈哈QIQ12 小时前
2025.7.19卡码刷题-回溯算法-组合
算法