链表是否是回文串

思想:找到中间位置,中间位置以后逆序,然后从中间位置的下一个结点开始与头结点开始向后比较,如果不相等直接返回false,否则返回true,这个题的另一个考点就是如何计算中间节点,其实很简单,定义一个快慢指针,快指针变化幅度是慢指针的二倍,结束后慢指针的位置就是中间节点的位置。

代码如下:

public static boolean isPalindrome(ListNode1 head) {
        //为空或者1个,直接返回true
        if(head == null || head.next == null) {
            return true;
        }
        //利用快慢指针找到中点
        ListNode1 fast = head;
        ListNode1 slow = head;
        while(fast!=null&&fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        slow = reverse(slow.next);
        while(slow!=null) {
            if(slow.data != head.data) {
                return false;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;
    }
    
    public static ListNode1 reverse(ListNode1 head) {
        if(head == null) {
            return head;
        }
        ListNode1 newHead = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

猜你喜欢

转载自www.cnblogs.com/duy666/p/10534340.html
今日推荐