题解 | 链表的回文结构
链表的回文结构
https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class PalindromeList {
public boolean chkPalindrome(ListNode head) {
// write code here
ListNode fast = head;
ListNode slow = head;
ListNode headA = head;
// 找到中间节点
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
// 开始反转中间节点之后
// cur 表示当前要反转的节点
// curN 记录cur后面的节点,避免反转后丢失
// slow 表示反转后cur节点的下一个节点
ListNode cur = slow.next;
while(cur != null){
ListNode curN = cur.next;
cur.next = slow;
slow = cur;
cur = curN;
}
//两头分别向后走,判断是不是回文结构,奇数直到相遇,偶数直到headA.next = slow;
while(headA != slow){
if(headA.val != slow.val){
return false;
}
if(headA.next == slow){
return true;
}
headA = headA.next;
slow = slow.next;
}
return true;
}
}
查看15道真题和解析