public static boolean isPalindrome(Node head) {
if (head == null || head.next == null) {
return true;
}
Node start = head;
Node end = head.next;
while (end != null && end.next != null) {
start = start.next;
end = end.next.next;
}
if (end != null) {
start = start.next;
}
cut(head, start);
boolean flag = isEqual(head, reserve(start));
return flag;
}
private static boolean isEqual(Node head, Node reserve) {
while (head != null && reserve != null) {
if (head.value != reserve.value) {
return false;
}
head=head.next;
reserve=reserve.next;
}
return true;
}
private static Node reserve(Node start) {
Node newNode = null;
while (start != null) {
Node Temp = start.next;
start.next = newNode;
newNode = start;
start = Temp;
}
return newNode;
}
private static void cut(Node head, Node start) {
if (head != start) {
head = head.next;
}
head.next = null;
}
回文链表
最新推荐文章于 2024-04-29 19:24:10 发布