234. 回文链表
题目
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
代码
法一、O(n)额外空间,转成数组后,对撞指针判断是否回文
/**
* 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 {
private:
static const int N = 1e5+5;
vector<int> q;
public:
bool isPalindrome(ListNode* head) {
q.assign(N, 0);
ListNode* p = head;
int x = 0;
while(p) {
q[x++] = p->val;
p = p->next;
}
for (int l = 0, r = x-1; l < r; ) {
if (q[l] != q[r]) {return false;}
l++, r--;
}
return true;
}
};
法二、递归,其实仍然需要O(n)空间
/**
* 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 {
private:
ListNode* l;
bool solve(ListNode* r) {
if (!r) {return true;}
if (!solve(r->next)) {return false;}
if (l->val != r->val) {return false;}
l = l->next;
return true;
}
public:
bool isPalindrome(ListNode* head) {
l = head;
ListNode* r = head;
return solve(r);
}
};
递归的方法,缺点是当l和r相遇后,无法终止比较,因为递归已经把“半段所有节点”都压栈了,所以回溯时无法阻止后面的调用继续返回。不过似乎可以通过设置全局标志,然后递归时候if()判断直接return。没试,先这样就行。
C++中如果类成员变量不用public也不用private修饰,默认还是private。和java一样,c++中也有protected:
| 关键字 | 含义 |
|---|---|
public |
所有地方都能访问 |
protected |
本类 + 子类可以访问 |
private |
只有本类可以访问 |

浙公网安备 33010602011771号