234. 回文链表
自己写的:
/**
* 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 *cur = head;
int cnt = 0;
while (cur)
{
++cnt;
cur = cur->next;
}
vector<int> v(cnt, 0);
cur = head;
int index = -1;
while (cur)
{
v[++index] = cur->val;
cur = cur->next;
}
for (int i = 0, j = cnt - 1; i < j; ++i, --j)
{
if (v[i] != v[j])
return false;
}
return true;
}
};
这里先求出了链表长度,然后用这个长度去开了个vector,相当于一次性开好。
开了个vector,不是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) {
if (head == nullptr || head->next == nullptr)
return true;
ListNode *slow = head;
ListNode *fast = head;
ListNode *pre = head;
while (fast && fast->next)
{
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = nullptr;
ListNode *cur1 = head;
ListNode *cur2 = reverseList(slow);
while (cur1)
{
if (cur1->val != cur2->val)
return false;
cur1 = cur1->next;
cur2 = cur2->next;
}
return true;
}
ListNode *reverseList(ListNode *head)
{
ListNode *pre = nullptr;
ListNode *cur = head;
while (cur)
{
ListNode *tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
其中反转链表部分和206.反转链表一样。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效