目录
一、回文链表
1.1 题目
牛客网原题链接:链表的回文结构_牛客题霸_牛客网
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
1.2 题解
class PalindromeList {
public:
//寻找中间节点
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
//逆置链表
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL) {
return head;
}
struct ListNode* a = NULL;
struct ListNode* b = head;
struct ListNode* c = head->next;
while (b) {
b->next = a;
a = b;
b = c;
if (c) {
c = c->next;
}
}
return a;
}
//
bool chkPalindrome(ListNode* A) {
struct ListNode* mid = middleNode(A);
struct ListNode* rmid = reverseList(mid);
while(rmid&&A)
{
if(rmid->val!=A->val)
{
return false;
}
rmid=rmid->next;
A = A->next;
}
return true;
}
};
1.3 分析
找到中间节点,将中间节点往后的节点进行逆置,然后从中间节点开始遍历之后的节点与头节点进行比较。

寻找中间节点使用快慢指针法,逆置链表用三指针法。具体讲解详见博主的另一篇博客:http://t.csdnimg.cn/1mZ1x
二、带环链表I
2.1 题目
LeetCode原题链接:. - 力扣(LeetCode)
给你一个链表的头节点
head,判断链表中是否有环。如果链表中存在环 ,则返回true。 否则,返回false。

本文详细介绍了链表中的五个经典问题:回文链表的判断、带环链表的检测与求交点、相交链表的查找以及深度拷贝的实现,通过快慢指针和巧妙的算法优化来解决这些问题。
最低0.47元/天 解锁文章
411

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



