- Palindrome Linked List:[题目链接]https://leetcode.com/problems/palindrome-linked-list/)
AC code:
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
41
42
43
44struct ListNode* reverse(struct ListNode* head){
struct ListNode* pre = NULL;
struct ListNode* cur = head;
struct ListNode* next = NULL;
while (cur != NULL){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
// 1->2->2->1
bool isPalindrome(struct ListNode* head){
if (head == NULL || head->next == NULL) {
return true;
}
struct ListNode* fast = head, * slow = head;
// 通过快慢指针找到中间节点
while (fast->next !=NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
struct ListNode* p = slow->next; // p: 2->1
slow->next = NULL; // 将head: 1->2 的尾节点置NULL
p = reverse(p); // 逆转p p: 1->2
// 分别遍历 head:1->2 p:1->2
while (head != NULL && p!= NULL) {
if (head->val != p->val){
return false;
}
head = head->next;
p = p->next;
}
// // 当链表元素为奇数时 如果有剩余元素
// if (head != NULL || p != NULL) {
// return true;
// }
return true;
}