题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
if(head == null) return false;
if(head.next == null) return true;
ListNode tmp = head;
int length = 1;
while(tmp.next != null) {
tmp = tmp.next;
length++;
}
ListNode fast = head;
ListNode slow = head;
for(int i = 0; i<length/2; i++) {
fast = fast.next;
}
if(length%2==1) fast = fast.next;
ListNode pre = new ListNode(-1);
for(int i = 0; i<length/2; i++){
ListNode next = slow.next;
slow.next = pre.next;
pre.next = slow;
slow = next;
}
pre = pre.next;
while(fast.next!=null){
if(pre.val == fast.val) {
pre = pre.next;
fast = fast.next;
}else return false;
}
return true;
}
}

查看23道真题和解析
美团成长空间 2640人发布