题目链接: 回文链表
有关题目


提示:
链表中节点数目在范围[1, 10^5] 内
0 <= Node.val <= 9
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
题解
法一:数组 + 双指针
/**
* 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 cnt = 0;
vector<int> a;
while(head != nullptr){
a.push_back(head->val);//a.emplace_back(head->val)
head = head->next;
}
int l = 0, r = a.size() - 1;
while(l < r){
if (a[l++] != a[r--]){
return false;
}
}
return true;
}
};

法二:递归
参考官方题解
/**
* 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 {
ListNode* frontPointer;
public:
bool recursivelyCheck(ListNode* currentNode){
if (currentNode != nullptr){
if (!recursivelyCheck(currentNode->next)) return false;
if (frontPointer->val != currentNode->val) return false;
frontPointer = frontPointer->next;
}
return true;
}
bool isPalindrome(ListNode* head) {
frontPointer = head;
return recursivelyCheck(head);
}
};

法三:快慢指针
参考官方题解
/**
* 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) {
//找到前半部分的尾节点 并反转后半部分链表
ListNode* firstHalfEnd = endOfFirstHalf(head);
ListNode* secondHalfStart = reverseList(firstHalfEnd->next);
//判断是否为回文
ListNode* p1 = head;
ListNode* p2 = secondHalfStart;
bool res = true;
while(res && p2 != nullptr){//注意p2 结束条件为 p2 != nullptr
if (p1->val != p2->val){
res = false;
}
p1 = p1->next, p2 = p2->next;
}
//还原原链表并返回结果
firstHalfEnd->next = reverseList(secondHalfStart);
return res;
}
ListNode* reverseList(ListNode* head){
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur != nullptr){
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
ListNode* endOfFirstHalf(ListNode* head){
ListNode* first = head;
ListNode* second = head;
while(first->next != nullptr && first->next->next != nullptr){
first = first->next->next;
second = second->next;
}
return second;
}
};

本文提供三种方法解决回文链表问题:使用数组结合双指针验证;采用递归方式对比链表前后节点值;借助快慢指针技巧反转链表后半部分进行比较。适用于链表节点数量在[1,10^5]范围内。
716

被折叠的 条评论
为什么被折叠?



