1、回文链表
给定一个链表的头节点 head
,请判断其是否为回文链表。如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
示例:
输入: head = [1,2,3,3,2,1] 输出: true
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//代码已经走到中间位置
ListNode cur = slow.next;
while(cur != null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//slow已经在最后一个节点了
while(head != slow){
if(head.val != slow.val){
return false;
}
if(head.next == slow){
return true;
}
//当为偶数时
head = head.next;
slow = slow.next;
}
return true;
}
}