【leetcode hot 100 234】回文链表

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

/**
 * 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;
    }
}

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

在这里插入图片描述

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

/**
 * 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;
    }
}

二刷

  • 使用LinkedList(按顺序查找访问)会超时,ArrayList(随机访问)就不会超时,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值