题解 | #链表的回文结构#

链表的回文结构

https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class PalindromeList {
    public boolean chkPalindrome(ListNode A) {
        // write code here
        ListNode fast = A;
        ListNode slow = A;
        while (!(fast == null || fast.next == null)) {
            fast = fast.next.next;
            slow = slow.next;
        }

        ListNode tmp = slow.next;
        while(tmp != null){
            ListNode p = tmp.next;
            tmp.next = slow;
            slow = tmp;
            tmp = p;
        }

        ListNode head = A;
        ListNode end = slow;

        while (head != end) {
            if (head.val != end.val) {
                return false;
            }
            if (head.next == end) {
                return true;
            }
            head = head.next;
            end = end.next;
        }
        return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务