LeetCode234. 回文链表(2024秋季每日一题 26)
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法一:通过数组记录,然后遍历判断是否回文
时间复杂度:
O
(
N
)
O(N)
O(N)
空间复杂度:
O
(
N
)
O(N)
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 {
public:
bool isPalindrome(ListNode* head) {
vector<int> res;
while(head != nullptr){
res.push_back(head -> val);
head = head -> next;
}
int n = res.size();
for(int i = 0; i < n / 2; i++){
if(res[i] != res[n-i-1])
return false;
}
return true;
}
};
解法二:
- 计算出原链表的节点个数,找到后半部分头结点
- 将后半部分链表反转,并记录翻转后的后半部分链表的头结点
- 同时遍历前后两个链表,判断是否回文
时间复杂度:
O
(
N
)
O(N)
O(N)
空间复杂度:
O
(
1
)
O(1)
O(1)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head -> next == nullptr) return true;
// 计算出总节点数
int cnt = 0;
ListNode* lh = head, * rh = head;
while(head != nullptr){
cnt++;
head = head -> next;
}
// 找到后半部分的头结点
for(int i = 1; i <= cnt / 2; i++){
rh = rh->next;
}
// 记录左边结束的位置
ListNode* ed = rh;
// 反转后半部分链表
ListNode* pre = nullptr, *ne;
while(rh != nullptr){
ne = rh -> next;
rh->next = pre;
pre = rh;
rh = ne;
}
rh = pre; // 翻转后后半部分的头结点
// 遍历两个部分,判断是否是回文
while(lh != ed){
if(lh->val != rh->val)
return false;
lh = lh -> next;
rh = rh -> next;
}
return true;
}
};
原文地址:https://blog.csdn.net/qq_46456049/article/details/142502302
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!