对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
Code
//coding=utf8 /***************************************************** @Author: Alex @Created Time : Tue 03 Sep 2019 07:36:51 AM CST @File Name: palindromeList.java @Blog: https://blog.csdn.net/weixin_43336281 ****************************************************/
public class palindromeList{
public static class Node{
public int value;
public Node next;
public Node(int data){
this.value = data;
}
}
public static boolean isPalindrome(Node head){
if(head == null || head.next == null)
return true;
Node n1 = head;
Node n2 = head;
while(n2.next != null && n2.next.next != null){
n1 = n1.next;
n2 = n2.next.next;
}
n2 = n1.next;
n1.next = null;
Node n3 = null;
while(n2 != null){
n3 = n2.next;
n2.next = n1;
n1 = n2;
n2 = n3;
}
n3 = n1; //n3 is last node
n2 = head;
boolean res = true;
while(n1 != null && n2 != null){
if(n1.value != n2.value){
res = false;
break;
}
n1 = n1.next;
n2 = n2.next;
}
n1 = n3.next;
n3.next = null;
while(n1 != null){
n2 = n1.next;
n1.next = n3;
n3 = n1;
n1 = n2;
}
return res; } }