【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;
    }
}
相关推荐
2401_8795034111 分钟前
C++中的观察者模式变体
开发语言·c++·算法
阿贵---30 分钟前
C++中的备忘录模式
开发语言·c++·算法
setmoon2141 小时前
C++中的观察者模式实战
开发语言·c++·算法
2403_835568471 小时前
C++代码规范化工具
开发语言·c++·算法
tankeven1 小时前
HJ138 在树上游玩
c++·算法
lihihi2 小时前
P1209 [USACO1.3] 修理牛棚 Barn Repair
算法
weixin_387534222 小时前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
xsyaaaan2 小时前
leetcode-hot100-链表
leetcode·链表
庞轩px2 小时前
MinorGC的完整流程与复制算法深度解析
java·jvm·算法·性能优化
Queenie_Charlie2 小时前
Manacher算法
c++·算法·manacher