Title description
For a linked list, please design an algorithm with a time complexity of O(n) and an additional space complexity of O(1) to determine whether it is a palindrome.
Given the head pointer A of a linked list, please return a bool value indicating whether it is a palindrome. Ensure that the length of the linked list is less than or equal to 900.
测试样例:
1->2->2->1
返回:true
Code:
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class PalindromeList {
public boolean chkPalindrome(ListNode head) {
// write code here
if (head == null){
return false;
}
// write code here
//1.找到链表的中间节点
ListNode fast = head;
ListNode slow = head;
while (fast !=null && fast.next != null){
fast =fast.next.next;
slow = slow.next;
}
//2.翻转中间链表之后的节点
ListNode cur =slow.next;//此时slow的位置就是中间节点
while (cur != null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//3.对比是否是首尾相同的回文
while (slow != head){
//当他两没遇到时
if (slow.val != head.val){
return false;
}
if (head.next == slow){
//偶数情况下
return true;
}
slow = slow.next;
head = head.next;
}
return true;
}
}
result: