?要求链表长度为N,时间复杂度O(N),空间复杂度O(1)。
思路1:先遍历一边链表,将链表放入栈中,再次遍历链表,用链表中的元素与栈中弹出的元素作比较,如果链表中的元素与栈中弹出的元素相等则是回文结构。空间复杂度O(N)
思路2:申明两个快慢指针(A和B)指向头节点,然后A指针一次走两步,B指针一次走一步,当A指针的Next.Next(下一步的下一步,此处应判断下一步是否为NULL)为NULL时,B指针刚好到中点,然后将B指针以后的元素压入栈中,再一次进行遍历链表,使遍历到的链表元素与栈中弹出的元素进行比较,如果链表中的元素与栈中弹出的元素相等则是回文结构。空间复杂度O(N/2)
思路3:申明两个快慢指针(A和B)指向头节点,然后A指针一次走两步,B指针一次走一步,当A指针的Next.Next(下一步的下一步,此处应判断下一步是否为NULL)为NULL时,B指针刚好到中点,此时将B的Next设置为NULL,再将其后面的节点指针反转,最后再次遍历链表(此处从链表表两端遍历),如果链表中的元素相等则是回文结构,最后还需要恢复链表结构。空间复杂度O(1),不建议使用
?
public class JZ {
static class Node {
private int number;
private Node next;
public Node(int number, Node next) {
this.number = number;
this.next = next;
}
}
public static void creatArr() {
JZ.Node node5 = new JZ.Node(1, null);
JZ.Node node4 = new JZ.Node(2, node5);
JZ.Node node3 = new JZ.Node(3, node4);
JZ.Node node2 = new JZ.Node(3, node3);
JZ.Node node1 = new JZ.Node(2, node2);
JZ.Node node0 = new JZ.Node(1, node1);
doFind(node0);
}
public static void doFind(Node node) {
Node quick = node;
Node slow = node;
/**
* 获取链表中点slow
*/
while (null != quick.next && null != quick.next.next) {
quick = quick.next.next;
slow = slow.next;
}
Node middle = slow;
Node end = null;
/**
* 如果链表长度是偶数时,end应指向最后一个节点
*/
if (null != quick.next) {
end = quick.next;
} else {
end = quick;
}
quick = slow.next;
slow.next = null;
Node aux = null;
/**
* 将中点slow以后的链表反转
*/
while (null != quick) {
aux = quick.next;
quick.next = slow;
slow = quick;
quick = aux;
}
/**
* 链表是否为回文结构
*/
slow = node;
Boolean isEquals = true;
quick = end;
while (null != slow && null != end) {
if (slow.number != end.number) {
isEquals = false;
break;
}
slow = slow.next;
end = end.next;
}
/**
* 链表还原
*/
end = quick.next;
quick.next = null;
while (end != middle) {
slow = end.next;
end.next = quick;
quick = end;
end = slow;
}
middle.next = quick;
System.out.println(isEquals);
}
public static void main(String[] args) {
creatArr();
}
}
|