题目描述
写这道题前最好把206.翻转链表 写了 有空间复杂度的话都好说,不管是新建链表、还是用字符串equals都好做。
思路 & 算法
快指针找终点,慢指针反转前半个链表 快指针回到慢指针的位置(中点,记得进行奇偶判断) 此刻,链表已经被分成两条以slow、fast开始的链表,遍历对比即可
class Solution {
public boolean isPalindrome ( ListNode head) {
ListNode fast = head, slow = head;
ListNode temp, pre = null ;
while ( fast != null && fast. next != null ) {
fast = fast. next. next;
temp = slow. next;
slow. next = pre;
pre = slow;
slow = temp;
}
fast = fast == null ? slow : slow. next;
slow = pre;
while ( slow != null ) {
if ( slow. val != fast. val) {
return false ;
}
slow = slow. next;
fast = fast. next;
}
return true ;
}
}
class Solution {
public boolean isPalindrome ( ListNode head) {
if ( head. next == null ) {
return true ;
}
ListNode slow = head, fast = head;
ListNode pre = null ;
while ( fast != null && fast. next != null ) {
fast = fast. next. next;
ListNode next = slow. next;
slow. next = pre;
pre = slow;
slow = next;
}
if ( fast != null ) {
slow = slow. next;
}
while ( pre != null ) {
if ( pre. val != slow. val) {
return false ;
}
pre = pre. next;
slow = slow. next;
}
return true ;
}
}