回文链表-快慢指针

31 阅读1分钟
// 回文链表-快慢指针  
// 输入:head = [1,2,2,1]  
// 输出:true  
public static boolean isPalindrome(ListNode head){  
    if(head==null){  
        return true;  
    }  
    ListNode firstHalfEnd=endOfFirstHalf(head);  
    ListNode secondHalfStart = reverList(firstHalfEnd.next);  
    ListNode p1=head;  
    ListNode p2=secondHalfStart;  
    boolean result=true;  
    while (result&&p2!=null){  
        if(p1.val!=p2.val){  
            return false;  
        }  
        p1=p1.next;  
        p2=p2.next;  
    }  
    firstHalfEnd.next=reverList(secondHalfStart);  
    return result;  
}  
  
private static ListNode reverList(ListNode head) {  
    ListNode prev=null;  
    ListNode curr=head;  
    while (curr!=null){  
        ListNode t=curr.next;  
        curr.next=prev;  
        prev=curr;  
        curr=t;  
    }  
    return prev;  
}  
  
    private static ListNode endOfFirstHalf(ListNode head) {  
    ListNode fast=head;  
    ListNode slow=head;  
    while (fast.next!=null&&fast.next.next!=null){  
        fast=fast.next.next;  
        slow=slow.next;  
    }  
    return slow;  
}