【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;
    }
}
相关推荐
原来是猿12 分钟前
蓝桥备赛(13)- 链表和 list(上)
开发语言·数据结构·c++·算法·链表·list
项目申报小狂人25 分钟前
高性能算法NGO!北方苍鹰优化算法(Northern Goshawk Optimization,NGO)
算法·数学建模
且听风吟ayan35 分钟前
leetcode day26 重复的子字符串
算法·leetcode·c#
仟濹1 小时前
【算法 C/C++】二维差分
c语言·c++·算法
*星星之火*1 小时前
【GPT入门】第9课 思维树概念与原理
gpt·算法·深度优先
总斯霖1 小时前
题解:士兵排列
数据结构·c++·算法
稳兽龙2 小时前
P4268 [USACO18FEB] Directory Traversal G
c++·算法·换根dp
我是大咖3 小时前
c语言笔记 一维数组与二维数组
c语言·笔记·算法
誓约酱3 小时前
(每日一题) 力扣 283 移动零
linux·c语言·数据结构·c++·算法·leetcode
Luis Li 的猫猫3 小时前
基于Matlab的人脸识别的二维PCA
开发语言·人工智能·算法·matlab