wrong了好多次就是过不了
过不了 画图板搞起!
成功AC
附代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next ==null) {
return true;
}
int size = 0;
ListNode p = head;
while (p != null) {
p = p.next;
size++;
}
ListNode pre = null;
ListNode cur = head;
ListNode nex = head;
ListNode headA = null;
int ans = size / 2;
for (int i = 0; i < ans; i++) {
nex = nex.next;
cur.next = pre;
pre = cur;
cur = nex;
}
headA = pre;
ListNode headB = (size % 2 == 0 ? cur : cur.next);
while (headA != null && headB!= null) {
if (headA.val != headB.val) {
return false;
}
headA = headA.next;
headB = headB.next;
}
return true;
}
}
求出链表长度
找到中点
长度为奇数则后半部分的链表头为cur.next(可以画图板模拟)
偶数则为cur
每个元素比较找到不同则返回false
遍历结束返回true
时间复杂度O(n)
空间复杂度O (1)