【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;
    }
}
相关推荐
IronMurphy7 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬7 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership7 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826527 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u8 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_11 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录12 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎12 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰12 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx12 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先