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)