判断一个链表是否为回文结构

利用快慢指针找到中点,之后进行反转。 反转之后使fast=head,比较值即可。不相同直接返回false,相同则继续进行比较,直到slow为false。比较完返回true即可。

public boolean isPail (ListNode head) {
        // write code here

        ListNode fast=head;
        ListNode slow=head;
        while (fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        slow=reverse(slow);
        fast=head;
        while (slow!=null){
            if(fast.val!=slow.val) return false;
            fast=fast.next;
            slow=slow.next;
        }
        return true;
    }

    public ListNode reverse(ListNode head){
        if(head==null) return head;

        ListNode cur=head;
        ListNode pre=null;
        while (cur!=null){
            ListNode tail=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tail;
        }
        return pre;
    }
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务