题解 | #判断一个链表是否为回文结构#

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

https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        if(head == null) return false;
        if(head.next == null) return true;
        ListNode tmp = head;
        int length = 1;
        while(tmp.next != null) {
            tmp = tmp.next;
            length++;
        }
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0; i<length/2; i++) {
            fast = fast.next;
        }
        if(length%2==1) fast = fast.next;
        ListNode pre = new ListNode(-1);
        for(int i = 0; i<length/2; i++){
            ListNode next = slow.next;
            slow.next = pre.next;
            pre.next = slow;
            slow = next;
        }
        pre = pre.next;
        while(fast.next!=null){
            if(pre.val == fast.val) {
                pre = pre.next;
                fast = fast.next;
            }else return false;
        }
        return true;
        
    }
}

全部评论

相关推荐

09-28 22:01
已编辑
广西科技大学 IT技术支持
合适才能收到offe...:找桌面运维?
点赞 评论 收藏
分享
notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务