欢迎来到 s a y − f a l l 的文章 欢迎来到say-fall的文章 欢迎来到say−fall的文章
文章目录
题目:链表的回文结构
- 牛客网:链表的回文结构

- 思路解析:
第一眼看到这个题目,想到的就是中间节点,因为是回文结构,而单链表又没有可以从尾遍历到头的方法,那我们下一个要解决的问题就是如何从中间节点下手对比前后部分
那我们现在有两个指针,一个是头指针,一个是中间节点的指针,链表的结构决定了我们只能让指针往后面走,这样的话就只能对中间节点的后面进行改造,那就自然而然地想到了反转链表这个算法
- 代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
// typedef struct ListNode ListNode;
ListNode* middleNode(ListNode* head)
{
ListNode* slow = head;
ListNode* fast = head;
while(fast != nullptr && fast->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
struct ListNode* reverseList(struct ListNode* head)
{
if(head == nullptr)
{
return nullptr;
}
ListNode* n1 = nullptr;
ListNode* n2 = head;
ListNode* n3 = head->next;
while(n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if(n3)
{
n3 = n3->next;
}
}
return n1;
}
bool chkPalindrome(ListNode* A)
{
if (A == nullptr || A->next == nullptr)
{ return true; }
ListNode* mid = middleNode(A);
mid = reverseList(mid);
int flag = 1;
ListNode* pcur = A;
while(mid)
{
if(mid->val != pcur->val)
{
flag = 0;
break;
}
mid = mid->next;
pcur = pcur->next;
}
return flag == 1;
}
};
- 本节完…

1188

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



