【链表】判断一个链表是否是回文链表_字符串

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

思路二:双指针

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

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

 

只要反转以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;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.