1.题目
有一个单向非循环链表,请判断它是否是回文结构。
回文结构的介绍:
链表的值延中间分开,是呈对称结构的。
2.分析
我们先利用快慢指针,找到链表的中间元素;
从中间元素开始,为新的链表,我们逆置这个新的链表与前半部分作比较。相同,返回true;不相同,返回fasle.
3.代码
import org.w3c.dom.NodeList;
/**
* Describe:
* User:lenovo
* Date:2023-01-05
* Time:22:57
*/
class Node {
int val;
Node next;
public Node() {
}
public Node(int val) {
this.val = val;
}
}
class MyLinkedList {
public Node head;
public MyLinkedList(Node head) {
this.head = head;
}
public MyLinkedList() {
}
}
public class Test {
public static boolean judgePalindromic(MyLinkedList list){
//链表为空
if(list == null || list.head == null) {
return true;
}
//找到中间节点
Node fast = list.head;
Node slow = list.head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//改变链表的指向
Node s1 = slow;
Node s2 = slow.next;
Node s3;
while(s2 != null) {
s3 = s2.next;
s2.next = s1;
s1 = s2;
s2 = s3;
}
//开始比较是否相同
slow.next = null;
Node nodeA = list.head;
Node nodeB = s1;
while(nodeA != slow) {
if(nodeA.val != nodeB.val) {
return false;
}else {
nodeA = nodeA.next;
nodeB = nodeB.next;
}
}
return true;
}
public static void main(String[] args) {
Node n1 = new Node(5);
Node n2 = new Node(8);
Node n3 = new Node(10);
Node n4 = new Node(8);
Node n5 = new Node(5);
//Node n6 = new Node(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
//n5.next = n6;
MyLinkedList myLinkedList = new MyLinkedList(n1);
System.out.println(judgePalindromic(myLinkedList));
}
}
先判断链表是否为空,为空直接返回true;
利用快慢指针找到链表的中间节点;
从中间节点开始,反转链表;
开始比较两个链表的值,不相同返回false,循环的结束条件为nodeA到达slow的位置结束。如果全部相等,返回true
4.总结
本题的重点在于快慢指针找中间节点、反转链表。难点在于链表的反转,链表的反转涉及三个节点,我们都依次记录,先记录容易被遗忘的节点,即s3 = s2.next;,这样s3节点就不会丢失,然后开始反转。
【易错点提醒】
判断相等时,循环的条件要注意,如果是两个中间节点,这连个中间节点也要判断是否相等。这里如果循环的条件是nodeB!=slow,这就将导致中间节点无法判断。