- 回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false
idea:先通过快慢指针找到中点,然后再通过反转链表反转后半部分,最后再比较两个链表值是否相等,最后可以还原一下
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode endoffirst=middle(head);
ListNode firstofright=reverse(endoffirst.next);
boolean flag=isPalindrome(head,firstofright);
return flag;
}
public ListNode middle(ListNode head){
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
public ListNode reverse(ListNode head){
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
public boolean isPalindrome(ListNode A,ListNode B){
while(B!=null){
if(A.val!=B.val){
return false;
}
A=A.next;
B=B.next;
}
return true;
}
}