/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
int n = 0 ; //统计节点的个数
for(ListNode *p = head ; p ; p = p->next) n++;
if(n <= 1) return true; //节点数<=1的一定是回文链表
//找到中点节点,由第一个节点跳(n+1)/2 -1步到达中点节点
ListNode* a = head;
for(int i = 0; i < (n+1)/2 - 1; i++) a = a->next; //a指针指向链表中点
ListNode* b = a->next; //b指针指向链表中点的下一个节点
while(b) //将链表的后半段反向
{
ListNode* next = b->next; //保留b的next节点
b->next = a;
a = b, b = next;
}6
//此时a指向链表的尾节点,我们让b指向链表的头节点
b = head;
ListNode* tail = a; //保留一下尾节点
bool res = true;
for(int i = 0; i < n/2; i++) //判断是否是回文链表
{
if(b->val != a->val)
{
res = false;
break;
}
b = b->next;
a = a->next;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40