import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
ListNode slow = head, fast = head;
while(fast != null){
slow = slow.next;
fast = fast.next;
if(fast != null)fast = fast.next;
}
ListNode rev = reverse(slow);
while(rev != null){
if(head.val != rev.val)return false;
rev = rev.next;
head = head.next;
}
return true;
}
private ListNode reverse(ListNode node){
ListNode pre = null, cur = node, next;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
用快慢指针找到链表的中间节点,翻转后半段链表,再进行比较,时间、空间复杂度最优。

京公网安备 11010502036488号