LeetCode234.回文链表(Java实现)

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

思路:

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

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

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

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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值