【链表】判断一个链表是否是回文链表

思路一:链表转为字符串,判断字符串是否是回文串

思路二:双指针

可以使用快慢指针,快指针的速度是慢指针的两倍,当快指针到达链表尾部时 ,慢指针到达中间位置。将慢指针之后的部分进行反转,再与前半部分比较

只要反转以slow.next为头结点的链表,与前面的比较即可。

public class Solution {
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    public boolean isPail (ListNode head) {
        // write code here
        if(head==null)return false;
        ListNode slow=head;
        ListNode fast=head;
        while(fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        ListNode q=reverse(slow.next);
        ListNode p=head;
        while(p!=null&&q!=null){
            if(p.val!=q.val){
                return false;
            }
            p=p.next;
            q=q.next;
        }
        return true;
      
    }
    public ListNode reverse(ListNode head){
        if(head==null)return null;
        ListNode dummyNode=new ListNode(0);
        ListNode p=head;
        while(p!=null){
            ListNode q=p.next;
            p.next=dummyNode.next;
            dummyNode.next=p;
            p=q;
        }
        return dummyNode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_52043808/article/details/124429075