// 回文链表-快慢指针
// 输入: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;
}
回文链表-快慢指针
最新推荐文章于 2024-07-22 14:15:06 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)