题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
public boolean isPail (ListNode head) {
// write code here
if (head == null || head.next == null){
return true;
}
//定义快慢指针
ListNode fast = head.next;
ListNode slow = head;
//快指针走两步,慢指针走一步
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//此时慢指针指向链表的中点,将链表断开
ListNode mid = slow.next;
slow.next = null;
//反转slow指向的链表,即链表的后半段
ListNode newHead = null;
while (mid != null){
ListNode temp = mid.next;
mid.next = newHead;
newHead = mid;
mid = temp;
}
//比较链表的前半段head和后半段newHead是否相等
while (head != null && newHead != null){
if (head.val != newHead.val){
return false;
}
head = head.next;
newHead = newHead.next;
}
return true;
}