补充一下求中点和翻转对比的代码

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

http://www.nowcoder.com/questionTerminal/3fed228444e740c8be66232ce8b87c2f

    public boolean isPail (ListNode head) {
        ListNode pre = head, cur = head;
        //求中点并进行反转后对比
        while (cur != null && cur.next != null) {
            cur = cur.next.next;
            pre = pre.next;
        }
        ListNode newHead = reverse(pre, cur);
        return isSame(head, newHead);
    }
    //翻转链表
    private ListNode reverse(ListNode head, ListNode tail) {
        ListNode pre = null, cur = head;
        while (cur != tail) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
    //判断是否相等
    private boolean isSame(ListNode head1, ListNode head2) {
        while (head1 != null && head2 != null) {
            if (head1.val != head2.val) return false;
            head1 = head1.next;
            head2 = head2.next;
        }
        return true;
    }
全部评论

相关推荐

我也曾抱有希望:说的好直白
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务