LeetCode234.回文链表(Java实现)

链接:https://leetcode-cn.com/problems/palindrome-linked-list/

思路:

先寻找中间节点,快慢指针寻找

然后将中间节点后续链表进行反转

最后前半段和后半段挨个比较即可

LeetCode234.回文链表(Java实现)_第1张图片

1.判空

2.设定中间节点,并寻找到中间节点

3.将中间节点下一跳作为头节点的链表进行反转(参考206题)

4.设定指针p1从head开始,p2从中间指针下一跳开始,挨个进行比较

5.在4循环中只要p1不为空且p2不为空,p1和p2后移一位

6.如果是回文链表,p2最终为空,否则不是

class Solution {
    public boolean isPalindrome(ListNode head) {
        //1.
        if(head==null || head.next==null){
            return true;
        }
        //2.
        ListNode middle = findMiddle(head);
        //3.
        middle.next = reverseList(middle.next);
        //4.
        ListNode p1 = head, p2 = middle.next;
        //5.    
        while (p1 != null && p2 != null && p1.val == p2.val) {
            p1 = p1.next;
            p2 = p2.next;
        }
        //6.
        return p2 == null;
    }
    private ListNode findMiddle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode h = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return h;
    }
}

 

你可能感兴趣的:(LeetCode编程题)